<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Session;
use think\Request;

class Wxapi extends Controller
{
    //用户登录获取openid和unionid
    function getopenid()
    {
        $code = input("post.code");
        $appid = input("post.appid");
        $appsecret = input("post.appsecret");
        $res = $this->lghcurl("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code");
        return json($res);
    }

    //获取所有轮播图信息
    function getslide()
    {
        $res = Db::table("lunbo")->where("status", "0")->limit(3)->select();
        return json($res);
    }

    //判断用户unionid是否存在,存在返回用户信息，否则返回0
    function checkunionid()
    {
        $unionid = input("post.unionid");
        $res = db("user")->where("unioid", $unionid)->find();
        return $res ? json($res) : 0;
    }

    //通过user_id获取用户信息
    function getuserinfo()
    {
        $user_id = input("post.user_id");
        $res = db("user")->where("user_id", $user_id)->find();
        return json($res);
    }

    //用户登录判断
    function login()
    {
        $phone = input("post.phone");
        $pass = input("post.pass");
        $userinfo = db("user")->alias('a')->join("userdata b", "a.user_id=b.uid")->where("phone", $phone)->find();
        /*
        0:手机号数据库里不存在
        1：密码错误
        其他返回用户数据
        */
        if (!$userinfo) {
            return 0;
        } else if (md5(md5($pass)) != $userinfo["pass"]) {
            return 1;
        } else {
            return json($userinfo);
        }
    }

    //检查判断验证码是否正确
    function check_code()
    {
        $phone = input("post.phone");
        $code = input("post.code");
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379, 1);
        $redis->auth("tiancheng123456");
        $str = $redis->get($phone);
        $redis->close();
        if ($str == $code) {
            return 1;//代表成功
        } else {
            return 0;//代表验证码错误
        }

    }

    //用户注册
    function register()
    {
        $phone = input("post.phone");
        $pass = input("post.pass");
        $pass = md5(md5($pass));
        $yaoqing = input("post.yaoqing");
        $referee_id = db("user")->where("phone", $yaoqing)->value("user_id");
        $referee_id = $referee_id ? $referee_id : "";
        $token = (string)time() . (string)$phone;
        $res = db("user")->insertGetId(["phone" => $phone, "pass" => $pass, "referee_id" => $referee_id, "token" => md5($token), "time" => time(), "status" => 0, "name" => $phone, "cishu" => 0, "is_vip" => 0]);
        return $res ? $res : "0";
    }

    //丢失密码重新设置
    function losspass()
    {
        $phone = input("post.phone");
        $pass = input("post.pass");
        $pass = md5(md5($pass));
        $res = db("user")->where("phone", $phone)->update(["phone" => $phone, "pass" => $pass]);
        if($res!=='false'){
            $user = db('user')->alias('a')->join('userdata b', 'a.user_id=b.uid ')->where(' phone=' . $phone)->find();
            $user['profile'] = !empty($user['profile']) ? $user['profile'] : '这个家伙很懒什么也没有';
            $count = db('follow')->alias('a')->join('class b', 'a.class_id=b.class_id')->where('a.uid', $user['user_id'])->count();
            $user['count'] = $count;
            $user['vip_endtime'] = date('Y-m-d');
            return json($user);
        }else{
            return 0;
        }
    }

    //设置用户数据
    function setdata()
    {
        $sex = input("post.sex");
        $birthday = input("post.birthday");
        $uid = input("post.uid");
        $flag = db("userdata")->where("uid", $uid)->find();
        if ($flag) {
            $res = db("userdata")->where("uid", $uid)->update(["sex" => $sex, "birthday" => $birthday]);
        } else {
            $res = db("userdata")->insert(["uid" => $uid, "sex" => $sex, "birthday" => $birthday]);
        }
        return $res ? 1 : 0;
    }

    //设置支付密码
    function setpaypass()
    {
        $paypass = input("post.paypass");
        $paypass = md5(md5($paypass));
        $uid = input("post.uid");
        $res = db("userdata")->where("uid", $uid)->update(["paypass" => $paypass]);
        return $res ? 1 : 0;
    }

    //发送短信验证码先判断是否已经注册
    function sendcode()
    {
        $phone = input("post.phone");
        $str = "0123456789";
        $str = str_shuffle($str);
        $code = substr($str, 0, 4);
        $check = db("user")->where("phone", $phone)->find();
        if ($check) {
            return "手机号已存在！";
        }
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379, 1);
        //$redis->auth("tiancheng123456");
        $redis->set($phone, $code);
        $redis->close();
        $a = new \alidy\SmsDemo($phone, $code);
        $a->sendSms();
        return "发送成功";
    }

    //忘记密码更改密码需要填的验证码
    function sendcodelosspass()
    {
        $phone = input("post.phone");
        $str = "0123456789";
        $str = str_shuffle($str);
        $code = substr($str, 0, 4);
        $check = db("user")->where("phone", $phone)->find();
        if (!$check) {
            return "手机号不存在！";
        }
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379, 1);
        $redis->auth("tiancheng123456");
        $redis->set($phone, $code);
        $redis->close();
        $a = new \alidy\SmsDemo($phone, $code);
        $a->sendSms();
        return "发送成功";
    }

    //获取一级分类
    function gettopcate()
    {
        $res = db("category")->where("pid=0 and name<>'推荐'")->limit(5)->select();
        return $res ? json($res) : '0';
    }
    //获取一级分类
    function gettopcateHome()
    {
        $res = db("category")->where("pid=0 and name<>'推荐'")->limit(3)->select();
        return $res ? json($res) : '0';
    }
    //通过一级分类id获取二级分类
    function gettwocate()
    {
        $pid = input("post.pid");
        $res = db("category")->where("pid", $pid)->select();
        return $res ? json($res) : 0;
    }

    //通过分类id获取所有店铺列表todo分页
    function getallclassbyid()
    {
        $pid = input("post.id");
        $page = input("post.page");
        $renqi = input("post.renqi");
        $yuyue = input("post.yuyue");
        $typestatus = input("post.typestatus");
        $order = '';
        $whereinfo = '';
        if ($renqi == 1) {
            $order = 'follow_num desc';
        } elseif ($renqi == 2) {
            $order = 'follow_num asc';
        }
        if ($yuyue == 1) {
            $order = 'yuyuesc desc';
        } elseif ($yuyue == 2) {
            $order = 'yuyuesc asc';
        }

        if ($typestatus == 3) {
            $whereinfo = 'a.type=3'; //机构
        } else {
            $whereinfo = 'a.type<>3';//名师
        }



        $str = $this->toPidGetStrCateid($pid);



//        $allid[] = $pid;
//        $str = implode(",", $allid);
        $allclass = db("class")->alias("a")->join("userdata b", "a.uid=b.uid and a.cate_id in ({$str})")->join("goods g", "a.class_id=g.class_id and g.type=3", "LEFT")->group("a.class_id")->field("a.*,b.image as headimg,count(a.class_id) as yuyuesc")->where($whereinfo)->limit($page * 10, 10)->order($order)->select();

//        echo db("class")->getlastsql();



        //一是判断是否有预约直播，二是从两个商品中取出来图片
        for ($i = 0; $i < count($allclass); $i++) {
            //通过店铺id 从goods获取 category_name
            $name = db("goods")->alias("a")->join("category b", "a.cate_id=b.cate_id")->where("class_id={$allclass[$i]['class_id']} and status=0")->group('a.cate_id')->order('number desc')->limit(4)->select();
            $namestr = '';
            foreach ($name as $k => $v) {
                $namestr .= $v['name'] . ',';
            }
            $allclass[$i]["catename"] = rtrim($namestr, ' , ');
            $allclass[$i]["catename"] = $allclass[$i]["catename"] ? $allclass[$i]["catename"] : '暂无';
            $allclass[$i]["teachername"] = $allclass[$i]["teachername"] ? $allclass[$i]["teachername"] : '暂无';
            //计算好评
//            $commotcount=db('comment')->where("class_id ={$allclass[$i]['class_id']} and star>=3")->count();
//            $allclass[$i]["commentcount"]=$commotcount?$commotcount:0;
            //计算销量 这个店铺的所有商品的销售
            $num = db('goods')->where("class_id={$allclass[$i]['class_id']} and status=0")->sum('number');
            if ($num) {
                $allclass[$i]["commentcount"] = rand('96', '100') . '%';
            } else {
                $allclass[$i]["commentcount"] = 0;
            }
            $allclass[$i]["countnumber"] = $num ? $num : 0;
            $flag = db("goods")->where("class_id={$allclass[$i]['class_id']} and `type`=6 and status=0")->find();
            $flag ? $allclass[$i]["flag"] = 1 : $allclass[$i]["flag"] = 0;
            $check = db("goods")->where("class_id={$allclass[$i]['class_id']} and status=0")->order("grounding_time desc")->limit(2)->select();
            $allclass[$i]["headimg"] = $allclass[$i]["headimg"] ? $allclass[$i]["headimg"] : "/user/public_morentouxiang.png";
            if (count($check) == 0) {
                $temp = array(
                    array("img" => "/user/public_zwkc.png"),
                    array("img" => "/user/public_zwkc.png")
                );
            } else if (count($check) == 1) {
                $check[0]["img"] = $check[0]["img"] ? $check[0]["img"] : "/user/public_zwkc.png";
                $check[] = array("img" => "/user/public_zwkc.png");
                $temp = $check;
            } else {
                $check[0]["img"] = $check[0]["img"] ? $check[0]["img"] : "/user/public_zwkc.png";
                $check[1]["img"] = $check[1]["img"] ? $check[1]["img"] : "/user/public_zwkc.png";
                $temp = $check;
            }
            $allclass[$i]["thum"] = $temp;
        }
        return json($allclass);
    }
    //通过分类id获取所有店铺列表todo分页
    function getallclassbyidzhibo()
    {
        $pid = input("post.id");
        $page = input("post.page");
        $renqi = input("post.renqi");//价钱
        $yuyue = input("post.yuyue");
        $typestatus = input("post.typestatus");
        $order = '';
        $whereinfo = '';
        if ($renqi == 1) {
            $order = 'follow_num desc';
        } elseif ($renqi == 2) {
            $order = 'follow_num asc';
        }
        if ($yuyue == 1) {
            $order = 'yuyuesc desc';
        } elseif ($yuyue == 2) {
            $order = 'yuyuesc asc';
        }

        if ($typestatus == 3) {
            $whereinfo = 'a.type=3'; //机构
        } else {
            $whereinfo = 'a.type<>3';//名师
        }
        $allid = $this->getallid($pid);
        $allid[] = $pid;
        $str = implode(",", $allid);



        $allclass = db("class")->alias("a")->join("userdata b", "a.uid=b.uid and a.cate_id in ({$str})")->join("goods g", "a.class_id=g.class_id and g.type=3", "LEFT")->group("a.class_id")->field("a.*,b.image as headimg,count(a.class_id) as yuyuesc")->where($whereinfo)->limit($page * 10, 10)->order($order)->select();


        //一是判断是否有预约直播，二是从两个商品中取出来图片
        for ($i = 0; $i < count($allclass); $i++) {
            //通过店铺id 从goods获取 category_name
            $name = db("goods")->alias("a")->join("category b", "a.cate_id=b.cate_id")->where("class_id={$allclass[$i]['class_id']} and status=0")->group('a.cate_id')->order('number desc')->limit(4)->select();
            $namestr = '';
            foreach ($name as $k => $v) {
                $namestr .= $v['name'] . ',';
            }
            $allclass[$i]["catename"] = rtrim($namestr, ' , ');
            $allclass[$i]["catename"] = $allclass[$i]["catename"] ? $allclass[$i]["catename"] : '暂无';
            $allclass[$i]["teachername"] = $allclass[$i]["teachername"] ? $allclass[$i]["teachername"] : '暂无';
            //计算好评
//            $commotcount=db('comment')->where("class_id ={$allclass[$i]['class_id']} and star>=3")->count();
//            $allclass[$i]["commentcount"]=$commotcount?$commotcount:0;
            //计算销量 这个店铺的所有商品的销售
            $num = db('goods')->where("class_id={$allclass[$i]['class_id']} and status=0")->sum('number');
            if ($num) {
                $allclass[$i]["commentcount"] = rand('96', '100') . '%';
            } else {
                $allclass[$i]["commentcount"] = 0;
            }
            $allclass[$i]["countnumber"] = $num ? $num : 0;
            $flag = db("goods")->where("class_id={$allclass[$i]['class_id']} and `type`=6 and status=0")->find();
            $flag ? $allclass[$i]["flag"] = 1 : $allclass[$i]["flag"] = 0;
            $check = db("goods")->where("class_id={$allclass[$i]['class_id']} and status=0")->order("grounding_time desc")->limit(2)->select();
            $allclass[$i]["headimg"] = $allclass[$i]["headimg"] ? $allclass[$i]["headimg"] : "/user/public_morentouxiang.png";
            if (count($check) == 0) {
                $temp = array(
                    array("img" => "/user/public_zwkc.png"),
                    array("img" => "/user/public_zwkc.png")
                );
            } else if (count($check) == 1) {
                $check[0]["img"] = $check[0]["img"] ? $check[0]["img"] : "/user/public_zwkc.png";
                $check[] = array("img" => "/user/public_zwkc.png");
                $temp = $check;
            } else {
                $check[0]["img"] = $check[0]["img"] ? $check[0]["img"] : "/user/public_zwkc.png";
                $check[1]["img"] = $check[1]["img"] ? $check[1]["img"] : "/user/public_zwkc.png";
                $temp = $check;
            }
            $allclass[$i]["thum"] = $temp;
        }
        return json($allclass);
    }
    //传个id过来递归返回id本身和下级分类
    function getallid($id)
    {
        static $arr = array();
        $flag = Db::table("category")->where("pid", $id)->select();
        if ($flag) {
            for ($i = 0; $i < count($flag); $i++) {
                $arr[] = $flag[$i]["cate_id"];
                $this->getallid($flag[$i]["cate_id"]);
            }
        }
        return $arr;
    }

    //加载视频列表通过cate_id
    function loadvideobycateid()
    {
        $class_id = input("post.id");
        $hot = input("post.hot");
        $price = input("post.price");
        $flaginfo = input("post.flaginfo");// 是否是免费
        $page = input("post.page") ? input("post.page") : 0;
        $order = '';
        $where = '';
        if ($flaginfo == 1) { //免费
            $where = " and (money IS NULL OR money=0)";
        }


        if ($hot == 1) {
            $order = 'number desc ';
        } elseif ($hot == 2) {
            $order = 'number asc ';
        }

        if ($price == 1) {
            $order = 'money desc  ';
        } elseif ($price == 2) {
            $order = 'money asc ';
        }


        $allid = $this->getallid($class_id);
        $allid[] = $class_id;
        $str = implode(",", $allid);


        $res = db("goods")->where("cate_id in({$str}) and `type` in (2,3) and status=0 " . $where)->order($order . 'grounding_time desc')->limit($page * 10, 10)->select();


        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["starttime"] = date("Y.m.d", $res[$i]["starttime"]);
            $res[$i]["endtime"] = date("Y.m.d", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);
            $uid = db("class")->where("class_id", $class_id)->value("uid");
            $res[$i]["headimg"] = db("userdata")->where("uid", $uid)->value("image");
            $res[$i]["nickname"] = db("user")->where("user_id", $uid)->value("name");
            $res[$i]["headimg"] = $res[$i]["headimg"] ? $res[$i]["headimg"] : "/user/public_morentouxiang.png";

        }
        return json($res);
    }

    //加载直播列表通过cate_id
    function loadzhibobycateid()
    {
        $class_id = input("post.id");

        $hot = input("post.hot");
        $price = input("post.price");
        $page = input("post.page") ? input("post.page") : 0;
        $order = '';
        if ($hot == 1) {
            $order = 'number desc ';
        } elseif ($hot == 2) {
            $order = 'number asc ';
        }

        if ($price == 1) {
            $order = 'discount_money desc ';
        } elseif ($price == 2) {
            $order = 'discount_money asc ';
        }


        $allid = $this->getallid($class_id);
        $allid[] = $class_id;
        $str = implode(",", $allid);
        $res = db("goods")->where("cate_id in({$str}) and `type` in (1,6) and status=0")->order($order)->select();
        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["video_length"] = floor($res[$i]["video_length"] / 60) . '分钟';
            $res[$i]["starttime"] = format_date($res[$i]["starttime"] - time());
            $res[$i]["endtime"] = date("Y.m.d", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);
            $uid = db("class")->where("class_id", $res[$i]["class_id"])->value("uid");
            $res[$i]["headimg"] = db("userdata")->where("uid", $uid)->value("image");
            $res[$i]["nickname"] = db("user")->where("user_id", $uid)->value("name");
            $res[$i]["headimg"] = $res[$i]["headimg"] ? $res[$i]["headimg"] : "/user/public_morentouxiang.png";

        }
        return json($res);
    }

    //加载视频列表通过class_id
    function loadvideobyid()
    {
        $class_id = input("post.id");
        $res = db("goods")->where("class_id={$class_id} and `type` in (2,3) and status=0")->order("grounding_time desc")->select();
        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["starttime"] = date("Y.m.d", $res[$i]["starttime"]);
            $res[$i]["endtime"] = date("Y.m.d", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);
            $uid = db("class")->where("class_id", $res[$i]["class_id"])->value("uid");
            $res[$i]["headimg"] = db("userdata")->where("uid", $uid)->value("image");
            $res[$i]["nickname"] = db("user")->where("user_id", $uid)->value("name");
            $res[$i]["headimg"] = $res[$i]["headimg"] ? $res[$i]["headimg"] : "/user/public_morentouxiang.png";

        }
        return json($res);
    }

    //加载直播列表通过class_id
    function loadzhibobyid()
    {
        $class_id = input("post.id");
        $res = db("goods")->where("class_id={$class_id} and `type` in (1,6) and status=0")->order("grounding_time desc")->select();

        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["video_length"] = floor($res[$i]["video_length"] / 60) . '分钟';
            $res[$i]["daojishi"] = format_date($res[$i]["starttime"] - time());
            $res[$i]["starttime"] = date("Y.m.d", $res[$i]["starttime"]);
            $res[$i]["endtime"] = date("Y.m.d", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);
            $uid = db("class")->where("class_id", $res[$i]["class_id"])->value("uid");
            $res[$i]["headimg"] = db("userdata")->where("uid", $uid)->value("image");
            $res[$i]["nickname"] = db("user")->where("user_id", $uid)->value("name");
            $res[$i]["headimg"] = $res[$i]["headimg"] ? $res[$i]["headimg"] : "/user/public_morentouxiang.png";

        }
        return json($res);
    }

    //加载预约列表通过class_id
    function loadyuyuebyid()
    {
        $class_id = input("post.id");
        $index = input("post.index"); //0代表今天 以此类推

        //推断出时间段
        if (!$index) { //如果是今天的话 只显示今天没有直播过的
            $daytime = time();
            $daytimeend = strtotime(date('Y-m-d', time())) + 24 * 3600;
            $where['endtime'] = array('between', array($daytime, $daytimeend)); //结束时间大于当前时间 就表明没有过期
        } else {
            $daytime = strtotime(date('Y-m-d', time())) + $index * 24 * 3600;
            $daytimenex = $daytime + 24 * 3600;
            $where['starttime'] = array('between', array($daytime, $daytimenex));
        }
        $where['class_id'] = $class_id;
        $where['type'] = 5;
        $where['status'] = 0;
        $res = db("goods")->where($where)->order("grounding_time desc")->select();
//        echo db("goods")->getLastSql();
        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["cate_namethr"] = cagid_getname($res[$i]["cate_id"]);//三级类别名字
            $res[$i]["cate_nametwo"] = cagid_getname(cagid_getpid($res[$i]["cate_id"]));//二级级类别名字
            $res[$i]["starttime"] = date("Y.m.d H:i:s", $res[$i]["starttime"]);
            $res[$i]["endtime"] = date("H:i:s", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);
            $uid = db("class")->where("class_id", $res[$i]["class_id"])->value("uid");
            $res[$i]["headimg"] = db("userdata")->where("uid", $uid)->value("image");
            $res[$i]["nickname"] = db("user")->where("user_id", $uid)->value("name");
            $res[$i]["headimg"] = $res[$i]["headimg"] ? $res[$i]["headimg"] : "/user/public_morentouxiang.png";
            $res[$i]["select"] = 'true';
        }
        $data['date_extend'] = date_extend(8, $index);
        $data['res'] = $res;
        return json($data);
    }

    //通过id获取指定店铺信息
    function getclassinfo()
    {
        $class_id = input("post.class_id");
        $uid = input("post.uid");
        $res = db("class")->where("class_id", $class_id)->find();
        $res['name'] = assoc_substr($res['name'],12);
        $res["follow_num"] = db("follow")->where("class_id", $class_id)->count();
        $res["introduce"] = assoc_substr($res["introduce"],140);
        $flag = db("follow")->where("class_id={$class_id} and uid={$uid}")->find();
        $flag ? $res["isfollow"] = 1 : $res["isfollow"] = 0;
        return json($res);
    }

//关注取消关注
    function follow()
    {
        $uid = input("post.uid");
        $class_id = input("class_id");
        $flag = input("post.flag");
        if ($flag == 0) {
            db("follow")->insert(["class_id" => $class_id, "uid" => $uid, "time" => time()]);
        } else {
            db("follow")->where("class_id={$class_id} and uid={$uid}")->delete();
        }
    }

    //获取推荐数据
    function gettuijiangoods()
    {
//        $res = db("goods")->where("recommend=1 and status=0")->limit(5)->select();
        $where['recommend']=1;
        $where['status']=0;
        $where['del_status']=0;
        $res= db("goods")->where($where)
            ->limit(2)
            ->order('time desc')
            ->select();
        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["starttime"] = date("Y.m.d H:i:s", $res[$i]["starttime"]);
            $res[$i]["endtime"] = date("H:i:s", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);

        }
        return json($res);

    }

    //获取文化教育课程数据
    function getwenhuajiaoyu()
    {
        $allid = $this->getallid(100);
        $allid[] = 100;
        $str = implode(",", $allid);
        $res = db("goods")->where("cate_id in ({$str}) and status=0")->order("grounding_time desc")->limit(2)->select();
        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["starttime"] = date("Y.m.d H:i:s", $res[$i]["starttime"]);
            $res[$i]["endtime"] = date("H:i:s", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);

        }
        return json($res);
    }

    //获取文化教育二级分类
    function getwenhuajiaoyutwocate()
    {
        $res = db("category")->where("pid=100")->select();
        return json($res);
    }

    //获取语言学习课程数据
    function getyuyanxuexi()
    {
        $category['pid']=0;
        $category['img']=array('neq','');
        $categoryinfo=  db('category')->where($category)->select();
        $all=array();
        foreach ($categoryinfo as $k=>$v){
            $str = $this->toPidGetStrCateid($v['cate_id']);
//            echo $str; exit();
            $wehrecategory['pid']=$v['cate_id'];
            $categoryinfo=  db('category')->where($wehrecategory)->field('cate_id,name')->limit(5)->select();
            foreach ($categoryinfo as $kk=>$vv){
                $categoryinfo[$kk]['name']=assoc_substr($vv['name'],4);
            }
            $str=$str?$str:0;
//            $allid[] = $v['cate_id'];
//            $str = implode(",", $allid);
            $res = db("goods")->where("cate_id in ({$str}) and status=0 and del_status=0")->order("grounding_time desc")->limit(2)->select();

            foreach ($res as $kk=>$vv){
                $res[$kk]["starttime"] = date("Y.m.d H:i:s", $vv["starttime"]);
                $res[$kk]["endtime"] = date("H:i:s",$vv["endtime"]);
                $res[$kk]["time"] = date("Y.m.d", $vv["time"]);
                $res[$kk]["sign_endtime"] = date("Y.m.d", $vv["sign_endtime"]);
                $res[$kk]["grounding_time"] = date("Y.m.d", $vv["grounding_time"]);
                $res[$kk]["lower_time"] = date("Y.m.d", $vv["lower_time"]);
            }
            $all[$k]['cate_id']=$v['cate_id'];
            $all[$k]['onename']=$v['name'];
            $all[$k]['catename']=$categoryinfo;
            $all[$k]['data']=$res;
        }

      return json($all);
    }
    function toPidGetStrCateid($pid_one){
       $twoselect= db('category')->where('pid',$pid_one)->select();
       $two_id='';
       $two_string='';
       foreach ($twoselect as $k=>$v){
            $two_id.=$v['cate_id'].',';
            $twoselect= db('category')->where('pid',$v['cate_id'])->select();
            $two_string.=$v['cate_id'].',';
            foreach ($twoselect as $kk=>$vv){
                $two_string.=$vv['cate_id'].',';
            }

        }
        $two_string=  rtrim($two_string, ",");
     return $two_string;
    }
    //获取语言学习二级分类
    function getyuyanxuexitwocate()
    {
        $res = db("category")->where("pid=2")->select();
        return json($res);
    }

    //获取办公效率课程数据
    function getbangongxiaolv()
    {
        $allid = $this->getallid(68);
        $allid[] = 68;
        $str = implode(",", $allid);
        $res = db("goods")->where("cate_id in ({$str}) and status=0")->order("grounding_time desc")->limit(2)->select();
        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["starttime"] = date("Y.m.d H:i:s", $res[$i]["starttime"]);
            $res[$i]["endtime"] = date("H:i:s", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);

        }
        return json($res);
    }

    //获取办公效率二级分类
    function getbangongxiaolvtwocate()
    {
        $res = db("category")->where("pid=68")->select();
        return json($res);
    }

    //获取职业发展课程数据
    function getzhiyefazhan()
    {
        $allid = $this->getallid(256);
        $allid[] = 256;
        $str = implode(",", $allid);
        $res = db("goods")->where("cate_id in ({$str}) and status=0")->order("grounding_time desc")->limit(2)->select();
        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["starttime"] = date("Y.m.d H:i:s", $res[$i]["starttime"]);
            $res[$i]["endtime"] = date("H:i:s", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);

        }
        return json($res);
    }

    //获取职业发展二级分类
    function getzhiyefazhantwocate()
    {
        $res = db("category")->where("pid=256")->select();
        return json($res);
    }

    //获取产品开发课程数据
    function getchanpinkaifa()
    {
        $allid = $this->getallid(380);
        $allid[] = 380;
        $str = implode(",", $allid);
        $res = db("goods")->where("cate_id in ({$str}) and status=0")->order("grounding_time desc")->limit(2)->select();
        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["starttime"] = date("Y.m.d H:i:s", $res[$i]["starttime"]);
            $res[$i]["endtime"] = date("H:i:s", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);

        }
        return json($res);
    }

    //获取产品开发二级分类
    function getchanpinkaifatwocate()
    {
        $res = db("category")->where("pid=380")->select();
        return json($res);
    }

    //获取我的观看记录
    function getmyviewlog()
    {
        $uid = input("post.uid");
        $res = db("history")->alias("a")->join("goods b", "a.cid=b.goods_id and a.uid={$uid} and b.status=0")->field("a.type as flag,a.time as viewtime,b.*")->order("a.time desc")->select();
        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["starttime"] = date("Y.m.d H:i:s", $res[$i]["starttime"]);
            $res[$i]["endtime"] = date("H:i:s", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);
            $res[$i]["viewtime"] = date("Y.m.d H:i:s", $res[$i]["viewtime"]);
            $uid = db("class")->where("class_id", $res[$i]["class_id"])->value("uid");
            $res[$i]["headimg"] = db("userdata")->where("uid", $uid)->value("image");
            $res[$i]["nickname"] = db("user")->where("user_id", $uid)->value("name");
            $res[$i]["headimg"] = $res[$i]["headimg"] ? $res[$i]["headimg"] : "/user/public_morentouxiang.png";

        }
        return json($res);
    }

    //添加history
    function addHistory(){
        $addwhere['uid'] =$where['uid']= input("post.uid");
        $addwhere['cid']=$where['cid']= input("post.goods_id");
        $addwhere['type']= input("post.typeinfo");
        $addwhere['time']=time();
        $findinfo=db('history')->field('cid')->where($where)->find();
        if(!$findinfo){
            $res=db('history')->insertGetId($addwhere);
        }else{
            $res=0;
        }
        return json($res);
    }

    //通过传过来的cate_id获取所有子分类
    function loadallcate()
    {
        $cate_id = input("post.id");
        $res = db("category")->where("cate_id", $cate_id)->find();
        $res["child"] = db("category")->where("pid", $res["cate_id"])->select();
        for ($i = 0; $i < count($res["child"]); $i++) {
            $res["child"][$i]["child"] = db("category")->where("pid", $res["child"][$i]["cate_id"])->select();
        }
        return json($res);
    }

    //加载收藏的视频列表通过uid
    function getmycollect()
    {
        $uid = input("post.uid");
        $res = db("subscribe")->alias("a")->join("goods b", "a.cid=b.goods_id and a.uid=$uid")->order("grounding_time desc")->select();
        for ($i = 0; $i < count($res); $i++) {
            $res[$i]["starttime"] = date("Y.m.d", $res[$i]["starttime"]);
            $res[$i]["endtime"] = date("Y.m.d", $res[$i]["endtime"]);
            $res[$i]["time"] = date("Y.m.d", $res[$i]["time"]);
            $res[$i]["sign_endtime"] = date("Y.m.d", $res[$i]["sign_endtime"]);
            $res[$i]["grounding_time"] = date("Y.m.d", $res[$i]["grounding_time"]);
            $res[$i]["lower_time"] = date("Y.m.d", $res[$i]["lower_time"]);
            $uid = db("class")->where("class_id", $res[$i]["class_id"])->value("uid");
            $res[$i]["headimg"] = db("userdata")->where("uid", $uid)->value("image");
            $res[$i]["nickname"] = db("user")->where("user_id", $uid)->value("name");
            $res[$i]["headimg"] = $res[$i]["headimg"] ? $res[$i]["headimg"] : "/user/public_morentouxiang.png";

        }
        return json($res);
    }

    //通过uid获取用户消息
    function getmynews()
    {
        $arraynew=array();
        $where['uid'] = input("post.uid");
        for ($i=0;$i<=2;$i++){ //通过type不同来获取 不同的消息类型
            $where['type']=$i;
            $res = db("news")->where($where)->order("time desc")->select();
            if(empty($res)){
                $arraynew[$i]['status']=1;
                $arraynew[$i]['content']='';
            }
            foreach ($res as $k2=>$v2){
                $arraynew[$i]['status']=1;
                $arraynew[$i]['content']=$res[0]['content'];//获取最后一条信息
                    if($v2['status']==0){
                        $arraynew[$i]['status']=0;
                        break;
                    }
            }
        }
        return json($arraynew);
    }
  //获取消息列表
    function  getnewsList(){
        $where['uid'] = input("post.uid");
        $where['type'] = input("post.flag");
        $res = db("news")->where($where)->order("time desc")->select();
        foreach ($res  as   $k=>$v){
            $res[$k]['time']=date('Y-m-d H:i:s',$v['time']);
        }
        return json($res);
    }
    //保存意见反馈
    function savefeedback()
    {
        $text = input("post.text");
        $contact = input("post.contact");
        $res = db("feedback")->insert(["text" => $text, "contact" => $contact, "time" => time()]);
        return $res ? 1 : 0;
    }

    //上传图片接口
    function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size' => 15678000, 'ext' => 'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
        if ($info) {
            $path = "/public/uploads/" . date("Ymd", time()) . "/" . $info->getFilename();
            $id = db("picture")->insertGetId(["path" => $path]);
            return json(array("id" => $id, "path" => $path));
        } else {
            // 上传失败获取错误信息
            echo $file->getError();
        }

    }

    //curl封装
    function lghcurl($curl, $https = true, $method = 'get', $data = null)
    {
        $ch = curl_init();//初始化
        curl_setopt($ch, CURLOPT_URL, $curl);//设置访问的URL
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置不需要头信息
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只获取页面内容，但不输出
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不做服务器认证
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不做客户端认证
        }
        if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, true);//设置请求是POST方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置POST请求的数据
        }
        $str = curl_exec($ch);//执行访问，返回结果
        curl_close($ch);//关闭curl，释放资源
        return $str;
    }

    //修改密码验老密码
    function savePass()
    {
        $pass = md5(md5(input('pass')));
        $user_id = input('user_id');
        $passinfo = db('user')->where("user_id", $user_id)->value('pass');
        if ($pass == $passinfo) {
            $data['res'] = 1;
            $data['msg'] = '验证成功';
        } else {
            $data['res'] = 0;
            $data['msg'] = '验证失败';
        }
        return json($data);
    }

    //确认密码修改
    function savePassSure()
    {
        $surenewpass = md5(md5(input('surenewpass')));
        $surenewpasssure = md5(md5(input('surenewpasssure')));
        $user_id = input('user_id');

        if ($surenewpass != $surenewpasssure) {
            $data['res'] = 0;
            $data['msg'] = '两次密码不同';
            return;
        }

        $info = Db::table('user')
            ->where('user_id', $user_id)
            ->update([
                'pass' => $surenewpass,
            ]);
        if ($info == 1) {
            $data['res'] = 1;
            $data['msg'] = '修改成功';
        } else {
            $data['res'] = 0;
            $data['msg'] = '修改失败';
        }
        return json($info);
    }

    //获取热门的机构
    function hotjigou()
    {
//      $allclass = db("class")->alias("a")->join("userdata b", "a.uid=b.uid and a.cate_id in ({$str})")->join("goods g","a.class_id=g.class_id and g.type=3","LEFT")->group("a.class_id")->field("a.*,b.image as headimg,count(a.class_id) as yuyuesc")->where($whereinfo)->limit($page*10,10)->order($order)->select();
        $where = 'a.type=3';
        $order = 'follow_num desc,yuyuesc desc';
        $allclass = db('class')->alias("a")->join("goods g", "a.class_id=g.class_id and g.type=3", "LEFT")->group("a.class_id")->where($where)->field("a.*,count(a.class_id) as yuyuesc")->order($order)->limit(2)->select();
        foreach ($allclass as $i => $key) {
            //通过店铺id 从goods获取 category_name
            $name = db("goods")->alias("a")->join("category b", "a.cate_id=b.cate_id")->where("class_id={$allclass[$i]['class_id']} and status=0")->group('a.cate_id')->order('number desc')->limit(4)->select();
            $namestr = '';
            foreach ($name as $k => $v) {
                $namestr .= $v['name'] . ',';
            }
            $allclass[$i]["catename"] = rtrim($namestr, ' , ');
            $allclass[$i]["catename"] = $allclass[$i]["catename"]? assoc_substr($allclass[$i]["catename"],16) : '暂无';
            $allclass[$i]["teachername"] = $allclass[$i]["teachername"] ? $allclass[$i]["teachername"] : '暂无';
            $num = db('goods')->where("class_id={$allclass[$i]['class_id']} and status=0")->sum('number');
            if ($num) {
                $allclass[$i]["commentcount"] = rand('96', '100') . '%';
            } else {
                $allclass[$i]["commentcount"] = 0;
            }
            $allclass[$i]["countnumber"] = $num ? $num : 0;
        }
        return json($allclass);
    }

    //获取最高菜单
    function gettopmenu()
    {
        $topmenu = db('category')->where("pid=0 and img <> ''")->limit(5)->select();
        return json($topmenu);
    }

    //获得教育咨询、
    function getNewsArticle()
    {
        $page = input('page');
        $info = db('news_article')->order('create_time desc')->limit(10)->select();
        foreach ($info as $k => $v) {
            $info[$k]['description'] = substrs($info[$k]['description'], 8);
            $info[$k]['create_time'] = date('Y-m-d H:i', $v['create_time']);
        }
        return json($info);
    }

    //相关课程
    function reclass()
    {
        $goods_id = input('goods_id');
        $cate_id = db('goods')->where('goods_id', $goods_id)->value('cate_id');
        $where['type'] = 3;
        $where['cate_id'] = $cate_id;
        $where['goods_id'] = array('not in', $goods_id);
        $goodslist = db('goods')->where($where)->select();
        foreach ($goodslist as $k => $v) {
            $goodslist[$k]['grounding_time'] = date('Y-m-d H:i:s', $v['grounding_time']);
            $goodslist[$k]['img'] = $goodslist[$k]['img'] ? 'http://wyk-img-1255995999.cos.ap-beijing.myqcloud.com' . $goodslist[$k]['img'] : 'http://wyk-img-1255995999.cos.ap-beijing.myqcloud.com/jifen/php5aaa06be0386a.jpg';
        }
        return json($goodslist);
    }

    //详情页的返回状态
    function detailstatus()
    {
        $goods_id = input('goods_id');
        $user_id = input('user_id');
        $payrel = db('payrecord')->where(array('uid' => $user_id, 'cid' => $goods_id))->find();
        $good = db('goods')->where(array('goods_id' => $goods_id))->find();
        if (!$payrel) { //查看是否购买过此商品   买有购买
            if ($good['money'] == 0 || empty($good['money'])) {
                $rel['status'] = '2';//如果此商品是0元则可以 直接显示   加入课程
            } else {
                $rel['status'] = '3';//如果此商品有价钱则需要 显示购买 正常
                //有价钱还要判断是什么类型的   用在单课上
                if ($good['price_status'] == 2) {
                    $rel['status'] = '4';//此商品有团购价钱
                } elseif ($good['price_status'] == 1) {
                    $rel['status'] = '5';//此商品有会员价
                }

            }
        } else {    //购买过
            $rel['status'] = '1';//如果已经买了此商品 前台下方 显示开始学习
        }
        return json($rel);
    }

    //评论列表显示状态
    function comment()
    {
        $user = db('user');
        $goods_id = input('goods_id');
        $user_id = input('user_id');
        $page = 0;
        $commentrel = db('comment')->where(array('uid' => $user_id, 'goods_id' => $goods_id))->find();
        $rel['subscribe'] = db('subscribe')->where(array('uid' => $user_id, 'cid' => $goods_id))->value('subscribe_id');
        if (!$commentrel) {
            $good = db('goods')->where(array('goods_id' => $goods_id))->find();
            if ($good['type'] == 4) {
                $goods_id = $good['topic_id'];
            }
            $payrecord = db('payrecord');
            $payrel = $payrecord->where(array('uid' => $user_id, 'cid' => $goods_id))->find();
            if ($payrel) {
                if ($payrel['pay'] == 0) {
                    $rel['canComment'] = '0';
                } else {
                    $rel['canComment'] = '1';
                }
            } else {
                $rel['canComment'] = '0';
            }
        } else {
            $rel['canComment'] = '0';
        }

        //如果找到评论 请找出来对应的topic_id
        $goods_id_info = db('goods')->field('goods_id')->where(array('topic_id' => $goods_id))->select();
        $goods_id_infostring = trim(implode(',', array_multi2singlearray($goods_id_info)) . ',' . $goods_id, ',');
        $pl = db('comment_goods');
        $plrel = $pl->where(array('goods_id' => $goods_id))->find();
        $rel['commentNum'] = $plrel['num'];
        $rel['totalStarNum'] = $plrel['star'];
        $where = ' goods_id in (' . $goods_id_infostring . ')';
        $count = db('comment')->where($where)->count();
        $date = db('comment')->where($where)->limit($page, 20)->select();
        if (empty($date)) {
            $rel['data'] = array();
        } else {
            foreach ($date as $k => $v) {
                $usrel = $user->where(array('user_id' => $v['uid']))->find();
                $udrel = db('userdata')->where(array('uid' => $v['uid']))->find();
                $rel['data'][$k]['uImgURL'] = (string)$udrel['image'];   //评论人头像
                $rel['data'][$k]['uName'] = assoc_substr((string)$usrel['name'], 5);     //评论人名字
                $starNum = (string)$v['star'];   //星数
                $starNum_not = 5 - (string)$v['star'];   //星数
                $rel['data'][$k]['commentTime'] = (string)date('Y年m月d日 H:i:s', $v['time']);   //评论时间
                $rel['data'][$k]['comminetInfo'] = assoc_substr((string)$v['content'], 80);  //评论内容
                if ($starNum) {
                    for ($i = 1; $i <= $starNum; $i++) {
                        $rel['data'][$k]['starNum'][] = 1;
                    }
                } else {
                    $rel['data'][$k]['starNum'] = '';
                }
                if ($starNum_not) {
                    for ($i = 1; $i <= $starNum_not; $i++) {
                        $rel['data'][$k]['starNum_not'][] = 1;
                    }
                } else {
                    $rel['data'][$k]['starNum_not'] = '';
                }

            }
        }

        $rel['commentNum'] = empty($rel['commentNum']) ? 1 : $rel['commentNum'];
        //用来给小程序循环星星 亮的星星
        $pfstarnum = (int)($rel['totalStarNum'] / $rel['commentNum']);
        if ($pfstarnum) {
            for ($i = 1; $i <= $pfstarnum; $i++) {
                $rel['pfstarnum'][] = $pfstarnum;
            }
        } else {
            $rel['pfstarnum'] = '';
        }
        //灰色星星
        $pfstarnum_not = 5 - (int)($rel['totalStarNum'] / $rel['commentNum']);
        if ($pfstarnum_not) {
            for ($i = 1; $i <= $pfstarnum_not; $i++) {
                $rel['pfstarnum_not'][] = $pfstarnum_not;
            }
        } else {
            $rel['pfstarnum_not'] = '';
        }
        $rel['pffront'] = round($rel['totalStarNum'] / $rel['commentNum'], 2);
        $rel['count'] = $count;
//        $rel['canComment']='1';//写死可以评论可以delete
        return json($rel);


    }

    //添加收藏   如果没有收藏则取消收藏  如果没收藏了 则收藏
    function addSubscript()
    {
        $db = db('subscribe');
        $where['cid'] = input('goods_id');
        $where['uid'] = input('user_id');
        $findscript = db('subscribe')->where($where)->find();
        if ($findscript) {
            $addscript = db('subscribe')->where($where)->delete();
            if ($addscript) {
                $addscript = 0;
            }
        } else {
            $addscript = db('subscribe')->insertGetId(['cid' => $where['cid'], 'uid' => $where['uid'], 'time' => time()]);
        }
        return $addscript;
    }

    //大纲
    function daganggoods()
    {
        $good_id = input('goods_id');
        $nowGoods_id = input('nowGoods_id');
        $where['topic_id'] = $good_id;
        $infogoods = db('goods')->where($where)->select();
        foreach ($infogoods as $k => $v) {
            $infogoods[$k]['introduce'] = assoc_substr( $infogoods[$k]['introduce'],30);
            if ($v['goods_id'] == $nowGoods_id) {
                $infogoods[$k]['showstatus'] = 1;
            } else {
                $infogoods[$k]['showstatus'] = 0;
            }
        }
        return json($infogoods);
    }

    //评论添加
    function sendpl()
    {
        $title = input('title');
        $starnum = input('starnum');
        $user_id = input('user_id');
        $goods_id = input('goods_id');
        $class_id = db('goods')->where('goods_id', $goods_id)->value('class_id');
        $comment_goods = db('comment_goods')->where('goods_id', $goods_id)->find();
        $info = db('comment')->insert(['content' => $title, 'star' => $starnum, 'uid' => $user_id, 'goods_id' => $goods_id, 'time' => time(), 'class_id' => $class_id]);
        //评论成功之后 需要到评论扩展表comment_goods 来累计加加star
        if ($comment_goods) {
            $info = db('comment_goods')->where('goods_id', $goods_id)->setInc('star', $starnum);
            $info = db('comment_goods')->where('goods_id', $goods_id)->setInc('num', 1);
        } else {
            $info = db('comment_goods')->insert(['star' => $starnum, 'num' => 1, 'goods_id' => $goods_id]);
        }
        return json($info);
    }

    //我的支付信息
    function payinfo()
    {
        $user_id = input('user_id');
        //充值
        $payrecordinfo1 = db('payrecord')->where('uid=' . $user_id . ' and ptype=0')->order('time desc')->select();
        //消费
        $payrecordinfo2 = db('payrecord')->where('uid=' . $user_id . ' and ptype=2')->order('time desc')->select();
        foreach ($payrecordinfo1 as $k => $v) {
            $payrecordinfo1[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
        }
        foreach ($payrecordinfo2 as $k => $v) {
            $payrecordinfo2[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
            $payrecordinfo2[$k]['source'] = assoc_substr($v['source'],30);
        }
        $data['chong'] = $payrecordinfo1;
        $data['xiao'] = $payrecordinfo2;
        return json($data);
    }

    //我的信息
    function myinfo()
    {
        $user_id = input('user_id');
        $user = db('user')->alias('a')->join('userdata b', 'a.user_id=b.uid ')->where(' user_id=' . $user_id)->find();
        $user['profile'] = !empty($user['profile']) ? $user['profile'] : '这个家伙很懒什么也没有';
        $count = db('follow')->alias('a')->join('class b', 'a.class_id=b.class_id')->where('a.uid', $user_id)->count();
        $user['count'] = $count;
        $user['vip_endtime'] = date('Y-m-d');
        return json($user);
    }

    //我的关注
    function myfollow($user_id)
    {
        $user_id = input('user_id');
        $follow = db('follow')->alias('a')->join('class b', 'a.class_id=b.class_id')->where('a.uid=' . $user_id)->select();
        foreach ($follow as $k => $v) {
            $follow[$k]['teacherimg'] = $v['teacherimg'] ? $v['teacherimg'] : '/jifen/php5aaa06be0386a.jpg';
            $follow[$k]['teachername'] = $v['teachername'] ? $v['teachername'] : '暂无';
            $num = db('goods')->where("class_id={$follow[$k]['class_id']} and status=0")->sum('number');
            $follow[$k]['countnumber'] = $num ? $num : 0;
            $follow[$k]['commentcount'] = rand('96', '100') . '%';
            $name = db("goods")->alias("a")->join("category b", "a.cate_id=b.cate_id")->where("class_id={$follow[$k]['class_id']} and status=0")->group('a.cate_id')->order('number desc')->limit(4)->select();
            $namestr = '';
            foreach ($name as $kk => $vv) {
                $namestr .= $vv['name'] . ',';
            }
            $follow[$k]["catename"] = $name ? rtrim($namestr, ' , ') : '暂无';
        }

        return json($follow);
    }

    //取消关注
    function deleteguan()
    {
        $followid = input('followid');
        $user_id = input('user_id');
        $dinfo = db('follow')->delete($followid);
        if ($dinfo) {
            return $this->myfollow($user_id);
        }
    }

    //签到点击
    function sigclick()
    {
        $user_id = input('user_id');
        $where['time'] = time();
        $where['uid'] = $user_id;
        $siginfo = db('sign')->insertGetId($where);
        db('userdata')->where('uid',$user_id)->setInc('integral',5);
        $user_info = $this->mysig($user_id);
        //为了同 app 那头 统一star
        $sigc = json_decode($user_info)->sigc;
        $whereupdate['sign_id'] = $siginfo;
        $siginfo = db('sign')->where($whereupdate)->update(['signday' => $sigc]);
        //为了同 app 那头 统一end
        return $user_info;
    }


    //我的签到
    function mysig($user_id)
    {
        $user_id = input('user_id');
        $siginfo = db('sign')->where('uid', $user_id)->select();
        $sigconnum = array();
        $sigc = array();
        $notsig = array();
        for ($i = 1; $i <= 1000; $i++) {
            $etime = strtotime(date('Y-m-d', time())) - $i * 24 * 3600 + 24 * 3600;
            $stime = strtotime(date('Y-m-d', time())) - $i * 24 * 3600;
            $where_array = ' uid=' . $user_id . ' and  time<=' . $etime . ' and time >=' . $stime;
            $sign = db('sign')->where($where_array)->find();
            if (!$sign) {
                break;
            } else {
                $sigconnum[] = $sign;
            }
        }
        //连续签到天数
        $contentsig = count($sigconnum) % 7;
        for ($i = 1; $i <= $contentsig; $i++) {
            $sigc[$i]['time'] = date('d', strtotime(date('Y-m-d', time())) - 24 * 3600 * $i);
        }
        $siginfos['sig'] = array_reverse($sigc);
        //7天 减去 连续签到天数
        for ($i = 1; $i <= 6 - count($siginfos['sig']); $i++) {
            $notsig[$i]['time'] = date('d', strtotime(date('Y-m-d', time())) + 24 * 3600 * $i);
        }
        $siginfos['notsig'] = $notsig;
        //今天状态
        $etime = strtotime(date('Y-m-d', time())) + 24 * 3600 + 24;
        $stime = strtotime(date('Y-m-d', time()));
        $where_array = ' uid=' . $user_id . ' and  time<=' . $etime . ' and time >=' . $stime;
        $sign = db('sign')->where($where_array)->find();
        if ($sign) {
            $today[1]['today'] = 1;
            $today[1]['status'] = 1;
        } else {
            $today[1]['status'] = 0;
        }
        $today[1]['time'] = date('d', time());
        $siginfos['today'] = $today;//今天状态

        if ($today[1]['status']) {
            $siginfos['sigstatus'] = 1;//今天签到状态
            $siginfos['sigc'] = count($siginfos['sig']) + 1;//今天签到 需要 添加今天
        } else {
            $siginfos['sigstatus'] = 0;//今天签到状态
            $siginfos['sigc'] = count($siginfos['sig']);//今天没有签到
        }

        $siginfos['getsigc'] = 7 - $siginfos['sigc'];//今天签到 需要 添加今天
        return json_encode($siginfos);
    }

    //我的积分
    function myscore()
    {
        $user_id = input('user_id');
        $integral = db('userdata')->where('uid', $user_id)->value('integral');
        return json($integral);
    }
    //我的积分
    function mymoney()
    {
        $user_id = input('user_id');
        $integral = db('userdata')->where('uid', $user_id)->value('money');
        return json($integral);
    }
    //获取类别
    function cateinfo()
    {
        $categorycinfo = [];
        $categoryinfo = [];

        $category = db('category')->field('name,cate_id')->where("pid=0 and img<>''")->select();
        foreach ($category as $k => $v) {
            $categoryinfo[] = $v['name'];
            $categoryc = db('category')->field('name')->where('pid', $v['cate_id'])->select();
            $categorycinfo[] = array_multi2singlearray($categoryc);
            $category_cate_id = db('category')->field('cate_id')->where('pid', $v['cate_id'])->select();
            $categorycinfo_cate_id_info[] = array_multi2singlearray($category_cate_id);
        }
        $cateinfo['one'] = $categoryinfo;
        $cateinfo['two'] = $categorycinfo;
        $cateinfo['two_id'] = $categorycinfo_cate_id_info;
        return json($cateinfo);
    }

    //证明
    static function prove()
    {
        $in['uid'] = input('user_id');
        $in['name'] = input('name');
        $in['cardnum'] = input('idcord');
        $in['phone'] = input('phone');
        $in['time'] = time();
        $in['email'] = input('email');
        $in['identity'] = input('shenf');
        $in['cate_id'] = input('twoinfo_id');
        return json(1);
    }
    //获取COS 配置项
    function config(){
        $data['Bucket']='wyk-img-1255995999';
        $data['Region']='ap-beijing';
        $data['SecretId']='AKIDbKwODypWj2RxKVxtxJl4KfvGgPatP7Nn';
        $data['SecretKey']='l2TFq6FC3movvqjbQbfhmnqqju0iHUcZ';
        return json($data);
    }

    //获取COS 配置项
//    function config()
//    {
//        $data['Bucket'] = 'sys-1252230039';
//        $data['Region'] = 'ap-chengdu';
//        $data['SecretId'] = 'AKID1EL6xg1sQp23vgb8mGZhw55yz30Umzyr';
//        $data['SecretKey'] = 'KYfr7HLHBvVVL4Fg0HEPdcVGY5X1X1Wy';
//        return json($data);
//    }

    //资质证明状态判断
    function zizhistatus()
    {
        $uid = input('user_id');
        $status = db('prove')->where('uid', $uid)->find();
        if ($status) {
            return $status['status'];
        } else {
            return 101;
        }
    }

    //老师资质提交
    function fromsubmitterch()
    {
        $in['uid'] = input('user_id');
        $in['photofront'] = input('idcardF');
        $in['photoback'] = input('idcardB');
        $in['photohold'] = input('idcardH');
        $in['photocertify'] = input('zz1');
        $in['name'] = input('name');
        $in['cardnum'] = input('idcord');
        $in['phone'] = input('phone');
        $in['time'] = time();
        $in['email'] = input('email');
        $in['identity'] = 1;
        $in['cate_id'] = input('twoinfo_id');
        $info = db('prove')->insertGetId($in);
        return json($info);
    }

    //学生资质提交
    function fromsubmitsduty()
    {
        $in['school_name'] = input('schoolname');
        $in['school_num'] = input('studynum');
        $in['gd_time'] = strtotime(input('fintime'));
        $in['uid'] = input('user_id');
        $in['photofront'] = input('idcardF');
        $in['photoback'] = input('idcardB');
        $in['photohold'] = input('idcardH');
        $in['photocertify'] = input('zz1');
        $in['name'] = input('name');
        $in['cardnum'] = input('idcord');
        $in['phone'] = input('phone');
        $in['time'] = time();
        $in['email'] = input('email');
        $in['identity'] = 0;
        $in['cate_id'] = input('twoinfo_id');
        $info = db('prove')->insertGetId($in);
        return json($info);
    }

    //精英资质提交
    function fromsubmitjingying()
    {
        $in['uid'] = input('user_id');
        $in['photofront'] = input('idcardF');
        $in['photoback'] = input('idcardB');
        $in['photohold'] = input('idcardH');
        $in['photocertify'] = input('zz1');
        $in['name'] = input('name');
        $in['cardnum'] = input('idcord');
        $in['phone'] = input('phone');
        $in['time'] = time();
        $in['email'] = input('email');
        $in['identity'] = 2;
        $in['cate_id'] = input('twoinfo_id');
        $info = db('prove')->insertGetId($in);
        return json($info);
    }

    //机构提交
    function fromsubmitjigou()
    {
        $in['uid'] = input('user_id');
        $in['photofront'] = input('idcardF');
        $in['photoback'] = input('idcardB');
        $in['photohold'] = input('idcardH');
        $in['photocertify'] = input('zz1');
        $in['name'] = input('name');
        $in['cardnum'] = input('idcord');
        $in['phone'] = input('phone');
        $in['time'] = time();
        $in['email'] = input('email');
        $in['cate_id'] = input('twoinfo_id');
        $in['outfit_name'] = input('jigouname');
        $in['outfit_introduce'] = input('jigouintr');
        $in['outfit_address'] = input('jigouaddress');
        $in['outfit_phone'] = input('jigouphone');
        $in['identity'] = 3;
        $info = db('prove')->insertGetId($in);
        return json($info);
    }

    //发布需求
    function sendescript()
    {
        $cate_id = input('cate_id');
        $cateinfo = db('category')->field('cate_id,name')->where('pid', $cate_id)->select();
        return json($cateinfo);
    }

    //添加发布的需求
    function sendneedadd()
    {
        $money = input('money');//价钱
        $cate_id = input('cate_id');//分类id
        $data = input('data');//听课日期
        $time = input('time'); //听课时间
        $inputvalue_textarea = input('inputvalue_textarea');//描述
        $inputvalue_time = input('inputvalue_time');//听课时长
        $sendAudioList = input('sendAudioList');//语音url
        $arrayimg = input('arrayimg');//多张图片字符串
        $longtime = input('longtime');//语音时长
        $uid = input('uid');
//添加demand
        $demand['uid'] = $uid;
        $demand['cate_id'] = $cate_id;
        $demand['starttime'] = strtotime($data . $time);
        $demand['endtime'] = $demand['starttime'] + $inputvalue_time * 60;
        $demand['time'] = time();
        $demand['price'] = $money;
        $demand['pay_status'] = 0;
        $demand['status'] = 0;

        $demand_id = db('demand')->insertGetId($demand);
//添加describe
        $describe['demand_id'] = $demand_id;
        $describe['time'] = time();
        $describe['content'] = json_encode($inputvalue_textarea);
        $describe['voice'] = $sendAudioList;
        $describe['img'] = $arrayimg;
        if ($longtime) {
            $describe['voice_time'] = (int)($longtime / 1000);
        }

        $describe = db('describe')->insertGetId($describe);
//添加order
        $order['uid'] = $uid;//用户id
        $order['pid'] = $demand_id;//课程id  或者  需求id
        $order['num'] =time().randomkeysletter(4);//订单号
        $order['time'] =time();//订单生成时间
        $order['money'] =$money;//订单金额
        $order['status'] =0;//状态  0 ：待支付    1：支付成功    2：已取消  3:已失效
        $order['type'] =2;//类型  1:一对一直播 2：单节视频 3：套课 4：套课中的视频 5：预约直播   6：一对多直播
        $order['buytype'] =1;//购买方式  1：普通   2：团购
        $order['paytype'] =0;//支付方式  0：约课币  1：支付宝  2：微信
        $order['classtype'] =1;//课程类型  0：买课订单  1：定制课订单
        $order['see_status'] =0;//查看状态   0：未查看   1：已查看
        $order['finish_status'] =0;//订单是否完成   0：待    1：完成   2：取消
        $order_id= db('order')->insertGetId($order);
        if ($demand_id && $describe&&$order_id) {
            $data=array();
            $data['demand_id'] = $demand_id;
            $data['order_id'] = $order_id;
            $data['order_num'] = $order['num'];
            return json($data);
        }
    }
    //发布需求支付订单
    function orderpay()
    {


        $uid= input('uid');
        $passval = md5(md5(input('val')));
        $order_id = input('order_id');
        $demand_id = input('demand_id');
        $usredata=db('userdata')->where('uid',$uid)->value('paypass');
        if($passval!=$usredata){ //支付密码判断
            $idinfo=0;
            return json($idinfo);
        };
        $orderwhere['order_id']=$order_id;
        $demandwhere['demand_id']=$demand_id;
        $order= db('order')->where($orderwhere)->update(['status'=>1]);
        $money= db('order')->where($orderwhere)->value('money');
        $idinfo= db('demand')->where($demandwhere)->update(['pay_status'=>1]);
        $demandinfo= db('demand')->where($demandwhere)->find();



        db('userdata')->where('uid',$uid)->setDec('money',$money);

        $payrecordind['uid'] =$uid;
        $payrecordind['type']=2;
        $payrecordind['time']=time();
        $payrecordind['income']=0;
        $payrecordind['cid']=$demand_id;
        $payrecordind['pay']=$demandinfo['price'];
        $payrecordind['source']='定制课定金支付';
        $payrecordind['ptype']=2;
        $payrecordind['classtype']=1;
        db('payrecord')->insertGetId($payrecordind);
        return json($idinfo);
    }
    //描述的详情
    function describeselect()
    {
        $demand_id = input('demand_id');
        $demand = db('demand')->where('demand_id', $demand_id)->find();
        $content = db('describe')->where('demand_id', $demand_id)->value('content');
        $integral = db('userdata')->where('uid', $demand['uid'])->value('money');
        if ($integral < $demand['price']) {
            $data['status'] = 0;//余额不足
        } else {
            $data['status'] = 1;
        }
        $data['integral'] = $integral;
        $data['price'] = $demand['price'];
        $data['content'] =json_decode($content);
        return json($data);
    }
   //生成订单
    function makeOrder(){
        $order=array();
        $demand_id = input('demand_id');
        $passval = md5(md5(input('val')));
        $ordernum = input('order');
        $price = input('price');
        $demandinfo = db('demand')->where('demand_id', $demand_id)->find();
        $usredata=db('userdata')->where('uid',$demandinfo['uid'])->value('paypass');
        db('userdata')->where('uid',$demandinfo['uid'])->setDec('integral',$price);
        if($passval!=$usredata){
            $idinfo=0;
            return json($idinfo);
        };
        $order['uid'] = $demandinfo['uid'];//用户id
        $order['pid'] = $demand_id;//课程id  或者  需求id
        $order['num'] =$ordernum;//订单号
        $order['time'] =time();//订单生成时间
        $order['money'] =$demandinfo['price'];//订单金额
        $order['status'] =0;//状态  0 ：待支付    1：支付成功    2：已取消  3:已失效
        $order['type'] =2;//类型  1:一对一直播 2：单节视频 3：套课 4：套课中的视频 5：预约直播   6：一对多直播
        $order['buytype'] =1;//购买方式  1：普通   2：团购
        $order['paytype'] =0;//支付方式  0：约课币  1：支付宝  2：微信
        $order['classtype'] =1;//课程类型  0：买课订单  1：定制课订单
        $order['see_status'] =0;//查看状态   0：未查看   1：已查看
        $order['finish_status'] =0;//订单是否完成   0：待    1：完成   2：取消
        $idinfo= db('order')->insertGetId($order);
        return json($idinfo);
    }




    //订单生成
    function  goodsOrderGetNum(){
        $user_id = input('user_id');//购买者 钱
        $goods_id = input('goods_id');
        $vip = input('vip');//是否是VIP 价钱
        $tuan = input('tuan'); //是否是团购价钱
        $ordernum = input('ordernum'); //订单号

        if($vip||$tuan){
            $file='discount_money';
        }else{
            $file='money';
        }
        if($tuan){
            $tuan=2;
        }else{
            $tuan=1;
        }
        $fileall='class_id,name,cate_id,type,'.$file;
        $goodsInfo= db('goods')->where('goods_id',$goods_id)->field($fileall)->find();
        $order['uid'] = $user_id;//用户id
        $order['pid'] = $goods_id;//课程id  或者  需求id
        $order['num'] =$ordernum;//订单号
        $order['time'] =time();//订单生成时间
        $order['money'] =$goodsInfo[$file];//订单金额
        $order['status'] =0;//状态  0 ：待支付    1：支付成功    2：已取消  3:已失效
        $order['type'] =$goodsInfo['type'];//类型  1:一对一直播 2：单节视频 3：套课 4：套课中的视频 5：预约直播   6：一对多直播
        $order['buytype'] =$tuan;//购买方式  1：普通   2：团购
        $order['paytype'] =0;//支付方式  0：约课币  1：支付宝  2：微信
        $order['classtype'] =0;//课程类型  0：买课订单  1：定制课订单
        $order['see_status'] =0;//查看状态   0：未查看   1：已查看
        $order['finish_status'] =0;//订单是否完成   0：待    1：完成   2：取消
        $idinfo= db('order')->insertGetId($order);
        return json($idinfo);
    }

    //支付接口
    function payrecordapi($pay_uid,$add_uid,$money,$goods_id,$classtype,$info){
        //减掉购买者money
        db('userdata')->where('uid',$pay_uid)->setDec('money',$money);
        //增加拥有者money
        db('userdata')->where('uid',$add_uid)->setInc('money',$money);
        //添加到payrecord 记录表
        $payrecordin['uid'] =$add_uid;
        $payrecordin['type']=1;
        $payrecordin['time']=time();
        $payrecordin['income']=$money;
        $payrecordin['cid']=$goods_id;
        $payrecordin['pay']=0;
        $payrecordin['source']=$info;
        $payrecordin['ptype']=2;
        $payrecordin['ctype']=2;
        $payrecordin['classtype']=$classtype;
        $payrecordin= db('payrecord')->insertGetId($payrecordin);
        //减少到payrecord 记录表
        $payrecordind['uid'] =$pay_uid;
        $payrecordind['type']=2;
        $payrecordind['time']=time();
        $payrecordind['income']=0;
        $payrecordind['cid']=$goods_id;
        $payrecordind['pay']=$money;
        $payrecordind['source']=$info;
        $payrecordind['ptype']=2;
        $payrecordind['ctype']=2;
        $payrecordind['classtype']=$classtype;
        $payrecordind=db('payrecord')->insertGetId($payrecordind);
        if($payrecordin&&$payrecordind){
            $data=1;
            return $data;
        }
    }

  //购买产品
    function goodsOrderPar(){
        $val = md5(md5(input('val')));//密码
        $user_id = input('user_id');//购买者
        $paypass =db('userdata')->where('uid',$user_id)->value('paypass');
        if($paypass!=$val){
            return json(101);
        }
        $goods_id = input('goods_id');
        $vip = input('vip');//是否是VIP 价钱
        $tuan = input('tuan'); //是否是团购价钱
        $order_id = input('orderid'); //订单id
        if($vip||$tuan){
            $file='discount_money';
        }else{
            $file='money';
        }
       $fileall='class_id,name,cate_id,type,'.$file;
       $goodsInfo= db('goods')->where('goods_id',$goods_id)->field($fileall)->find();
       $classInfo= db('class')->where('class_id',$goodsInfo['class_id'])->find();
       $this->payrecordapi($user_id,$classInfo['uid'],$goodsInfo[$file],$goods_id,0,$goodsInfo['name']);
       $where['order_id'] =$order_id;//状态  0 ：待支付    1：支付成功    2：已取消  3:已失效
       $res = db("order")->where($where)->update(["status" => 1]);
       return json($res);
    }
    function getUpass(){
        $user_id = input('user_id');//购买者
        $paypass =db('userdata')->where('uid',$user_id)->value('paypass');
        if($paypass==''){
            return json(101);
        }
    }
    //获取phone
    function  VerPhone(){
        $value = input('value');
        $phone = input('phone');
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379, 1);
        $redis->auth("tiancheng123456");
        $info= $redis->get($phone);
        $redis->close();
        if($value==$info){
            $data=1;
        }else{
            $data=0;
        }
        return json($data);
    }
    //设置支付密码
    function setpassword(){
        $user_id = input('user_id');
        $value= md5(md5(input('value')));
        $where['uid']=$user_id;
        $res = db("userdata")->where($where)->update(["paypass" => $value]);
        if($res==='false'){
            $data=0;
        }else{
            $data=1;
        }
        return json($data);
    }
    //获取积分商城信息
    function getLunboInfo(){
        $user_id = input('user_id');
        $lunbo=db('lunbo');
        $lunbolist=$lunbo->limit(4)->field('goods_id,img')->select();
        $userinfo=db('userdata')->where('uid',$user_id)->value('integral');
        $hot= db('good')->where('type',1)->limit(3)->select();
        $dui= db('good')->where('type',2)->limit(3)->select();
        $data['lunbo']=$lunbolist;
        $data['integral']=$userinfo;
        $data['hot']=$hot;
        $data['dui']=$dui;
        return json($data);
    }
    //商品详情
    function  good_details(){
        $good_id=input('good_id');
        $goodinfo= db('good')->where('good_id',$good_id)->select();
        return json($goodinfo);
    }
    //兑奖
    function  changeAwardSet(){
        $dbname=db('userdata');
        $good_id=input('good_id');
        $user_id=input('user_id');
        $good_price=db('good')->where('good_id',$good_id)->field('price,num,timeend')->find();
        $user_price=  $dbname->where('uid',$user_id)->field('integral')->find();
        $add_where['uid']=$user_id;
        $add_where['status']=1;
        $addres=db('address')->where($add_where)->find();
        if(strtotime($good_price['timeend'])<time()){
            $data=5;
            return json($data);
        }
        if($good_price['num']<=0){
            $data=4;
            return json($data);
        }
        if(!$addres['address_id']){
            $data=3;
            return json($data);
        }
        if($good_price['price']>$user_price['integral']){
            $data=0;
        }else{
            $dbname->where('uid',$user_id)->setDec('integral',$good_price['price']);
            db('good')->where('good_id',$good_id)->setDec('num',1);
            $whereid['uid']=    $user_id;
            $whereid['gid']= $good_id;  //商品id
            $whereid['time']=time(); //兑换时间
            $whereid['num']=randomkeys(10);   //订单号
            $whereid['money']=$good_price['price']; //金额
            $whereid['address_id']=$addres['address_id']; //地址id
            $whereid['status']=1;    // 1：待发货 2：待收货 3：已完成
            $idinfo= db('ierecord')->insertGetId($whereid);
            $data=1;
        }
        return json($data);
    }
    //通过用户id 获取 用户地址信息
    function toUidToGetAddressInfo(){
        $user_id=input('user_id');
        $whereadd['uid']=$user_id;
        $address = db('address')->where($whereadd)->order('status desc')->select();
        return json($address);
    }
    //设置地址
    function setAddress(){
        $addressArray=explode(',',input('cityArray')) ;
        $where['address'] =   input('addressDetails');
        $where['province'] =  $addressArray[0];
        $where['city'] =  $addressArray[1];
        $where['area'] =  $addressArray[2];
        $where['phone'] =   input('phone');
        $where['name'] =   input('userName');
        $where['uid'] =   input('user_id');
        $address_id =   input('address_id');
        if($address_id){

            $addressinfo= db('address')->where('address_id',$address_id)->update($where);
            if($addressinfo!==false){
                $data=1;
            }else{
                $data=0;
            }
        }else{
            $addressinfo= db('address')->insertGetId($where);
            if($addressinfo){
                $data=1;
            }else{
                $data=0;
            }
        }

        return json($data);
    }
    //通过address_id 获取 address 信息
    function toAddresssIdGetAddressInfo(){
         $address_id=input('address_id');
         $addressInfo=  db('address')->where('address_id',$address_id)->select();
         return json($addressInfo);
    }
    //删除地址
    function  toAddressIdToDeletAddress(){
        $address_id=input('address_id');
        $whereadd['uid']=input('user_id');
        $delete_info=  db('address')->delete($address_id);
        $addresInfo = db('address')->where($whereadd)->order('status desc')->select();
        $data['delete_info']=$delete_info;
        $data['addresInfo']=$addresInfo;
        return json($data);
    }
    //设置默认地址
    function  addressSetDefault(){
//        user_id: user_id, address_id: address_id
        $where['uid']=input('user_id');
        $address_id=input('address_id');
        $upwhere['status']=0;
        $addressUpdataInfo= db('address')->where($where)->update($upwhere);
        $setwhere['status']=1;
        db('address')->where('address_id',$address_id)->update($setwhere);
        $addresInfo = db('address')->where('uid', $where['uid'])->order('status desc')->select();
        return json($addresInfo);
    }
    //通过用户id 获取 ie信息
    function  toUidIdGetIeInfo(){
        $user_id=input('user_id');
        $ierecordinfo= db('ierecord')->where('uid',$user_id)->order('time desc')->select();
        foreach ($ierecordinfo as $k=>$v){
            $goodInfo=db('good')->where('good_id',$v['gid'])->find();
            $ierecordinfon[$k]['img']=$goodInfo['img'];
            $ierecordinfon[$k]['title']=$goodInfo['name'];
            $ierecordinfon[$k]['time']=date('Y-m-d H:i:s',$v['time']);
            $ierecordinfon[$k]['ierecord_id']=$v['idrecord_id'];
        }
        return json($ierecordinfon);
    }
    //兑换详情
    function ieddetail(){
        $ierecord['idrecord_id']=input('ieid');
        $ierecordinfo= db('ierecord')->where($ierecord)->find();
        foreach ($ierecordinfo as $k=>$v){
            $goodsingo=db('good')->where('good_id',$ierecordinfo['gid'])->find();
            $ierecordinfo['name']=$goodsingo['name'];
            $ierecordinfo['details']=$goodsingo['details'];
        }
        return json($ierecordinfo);
    }
    //获取商品信息和用户信息
  function  toGoodIdGetGoodInfo(){
        $goods_id=input('goods_id');
        $user_id=input('user_id');
        $goodsinfo= db('goods')->where('goods_id',$goods_id)->find();
        $goodsinfo['introduce']=assoc_substr($goodsinfo['introduce'],10);
        $userdatainfo= db('userdata')->field('money')->where('uid',$user_id)->find();
        $data['finfo']=$goodsinfo;
        $data['uinfo']=$userdatainfo['money']?$userdatainfo['money']:0;
        $data['ordernum']=time().randomkeysletter(4);
        return json($data);
  }

  function getOrderInfo($uid,$action){
      if($action==1){ //全部
      }elseif($action==2){//待支付
          $where['status']=0;
      }elseif($action==3){//托管中
          $where['classtype']=1;
      }elseif($action==4){//团购中
          $where['buytype']=2;
      }elseif($action==5){//已完成
          $where['status']=1;
      }elseif($action==6){//已取消
          $where['status']=2;
      }
      $where['uid']=$uid;
      $userOrderInfo=db('order')->where($where)->order('order_id desc')->select();
      foreach ($userOrderInfo as $k=>$v){
          $userOrderInfo[$k]['time']=date('Y-m-d',$v['time']);
          $report_where['order_id']=$v['order_id'];
          $report_where['uid']=$uid;
          $userOrderInfo[$k]['jubao']=db('report')->where($report_where)->value('report_id')?1:0;
          $ginfo=db('goods')->where('goods_id',$v['pid'])->find();
          $user=db('user')->where('user_id',$ginfo['teacher_id'])->find();
          $cateinfoone=db('category')->where('cate_id',$ginfo['cate_id'])->find();
          $cateinfotwo=db('category')->where('cate_id',$cateinfoone['pid'])->find();
          $userOrderInfo[$k]['img']=$ginfo['img'];
          $userOrderInfo[$k]['name']=$ginfo['name']? assoc_substr($ginfo['name'],15):'';
          $userOrderInfo[$k]['classtime']=date('Y-m-d H:i:s',$ginfo['starttime']).'--'.date('H:i:s',$ginfo['endtime']);
          $userOrderInfo[$k]['tearchname']=$user['name']?$user['name']:'';
          $userOrderInfo[$k]['teacherhead']=db('userdata')->where('uid',$ginfo['teacher_id'])->value('image');
          $userOrderInfo[$k]['catename']=$cateinfoone['name'].' | '.$cateinfotwo['name'];
          if($v['classtype']==1){ //需求发布
              $demandinfo=db('demand')->where('demand_id',$v['pid'])->find();
              $userOrderInfo[$k]['demand_content']=assoc_substr(json_decode(db('describe')->where('demand_id',$demandinfo['demand_id'])->value('content')),30);
              $userOrderInfo[$k]['catename']=db('category')->where('cate_id',$demandinfo['cate_id'])->value('name');
              $userOrderInfo[$k]['number']=$demandinfo['number'];
              $userOrderInfo[$k]['price']=$demandinfo['price'];
          }
      }
      return json($userOrderInfo);
  }

  //通过uid 获取order
    function  toUidgetOrderInfo(){
//        状态  0 ：待支付    1：支付成功    2：已取消  3:已失效
        $uid=input('uid');
        $action=input('action')?input('action'):1;
        return $this->getOrderInfo($uid,$action);
    }
    //通过订单id 删除 order
    function  toOrderIdToDeletAddress(){
     $orderid=   input('orderid');
     $action=   input('action');
     $uid=   input('uid');
     $info= db('order')->delete($orderid);
     return $this->getOrderInfo($uid,$action);
    }
    //添加举报
    function  reportAdd(){
        $add['uid']=   input('uid');
        $add['cate']=   input('chebox');
        $add['text']=   input('textarea');
        $add['img']=   input('dbs');
        $add['contact']=   input('inputinfo');
        $add['time']=   time();
        $add['status']=  0;
        $add['order_id']=   input('orderid');
        $reportid=db('report')->insertGetId($add);
        return json($reportid);
    }
   //通过 orderid 获取订单信息
    function  toOrderIdGetOrderInfo(){
         $order_id=input('orderid');
         $orderInfo=db('order')->where('order_id',$order_id)->find();
         return json($orderInfo);
    }
    //取消订单
    function  orderCancel(){
        $order_id=input('orderid');
        $uid=input('uid');
        $action=input('action')?input('action'):1;
        $orderInfo=db('order')->where('order_id',$order_id)->update(["status"=>2]);
        return $this->getOrderInfo($uid,$action);
    }
    //删除订单
    function  orderDelete(){
        $order_id=input('orderid');
        $uid=input('uid');
        $action=input('action')?input('action'):1;
        $orderInfo=db('order')->delete($order_id);
        return $this->getOrderInfo($uid,$action);
    }
    //支付订单
    function payOrder(){
        $porderid=input('porderid');
        $val=md5(md5(input('val')));
        $uid=input('uid');
        $action=input('action');
        $ordernfo= db('order')->where('order_id',$porderid)->find();
        $userdataInfo= db('userdata')->where('uid',$uid)->find();
        $goodsInfo= db('goods')->where('goods_id',$ordernfo['pid'])->find();
        $classInfo=db('class')->where('class_id',$goodsInfo['class_id'])->find();

        if(empty($userdataInfo['paypass'])){
            $data=101;
            return json($data);
        }
        if($val!=$userdataInfo['paypass']){
            $data=102;
            return json($data);
        }
        $this-> payrecordapi($uid,$classInfo['uid'],$ordernfo['money'],$ordernfo['pid'],0,$goodsInfo['name']);
        db('order')->where('order_id',$porderid)->update(["status"=>1]);
        return $this->getOrderInfo($uid,$action);

    }
    //我的课程
    function  getMyClass(){
        $classtype=input('typeinfo');
        $uid=input('user_id');
        if($classtype==2){//直播
            $where['b.type']=array('in','1,6');
        }
        if($classtype==3){//预约
            $where['b.type']=5;
        }
        $where['a.type']=2;
        $where['a.ptype']=2;
        $where['uid']=$uid;
        $payrecord= db("payrecord")->alias("a")->join("goods b","a.cid=b.goods_id")->where($where)->select();
        foreach ($payrecord as $k=>$v){
            $goodsInfo= db('goods')->where('goods_id',$v['cid'])->find();
            $class=db('class')->where('class_id',$goodsInfo['class_id'])->find();
            $cateInfoone=db('category')->where('cate_id',$goodsInfo['cate_id'])->find();
            $cateInfotwo=db('category')->where('cate_id',$cateInfoone['pid'])->find();
            $userdata= db('userdata')->where('uid',$goodsInfo['teacher_id'])->find();
            $user= db('user')->where('user_id',$goodsInfo['teacher_id'])->find();
            $payrecord[$k]['headimg']=$userdata['image']?$userdata['image']:'/jifen/php5aaa06be0386a.jpg';
            $payrecord[$k]['starttime']=date('Y-m-d H:i:s',$v['starttime']).'--'.date('H:i:s',$v['endtime']);
            $payrecord[$k]['classhour']=$v['classhour']?$v['classhour']:0;
            $payrecord[$k]['teachername']=$user['name']?$user['name']:'';
            $payrecord[$k]['catename']=$cateInfoone['name'] .'|'. $cateInfotwo['name'];
            $payrecord[$k]['classtype']=$class['type'];
        }
        return json($payrecord);
    }

    //我的课程定制课
    function  getMyClassDemand(){
        $date=array();
        $uid=input('user_id');
        $where['uid']=input('user_id');
        $where['status']=1;
        $demandInfo= db("demand")->where($where)->select();
        foreach($demandInfo as $k=>$v){
            $classInfo=db('class')->where('class_id',$v['class_id'])->find();
            $date[$k]['demandid']=$v['demand_id'];
            $date[$k]['time']=date('Y.m.d H:i',$v['starttime']).'-'.date('H:i',$v['endtime']);
            $cate=db('category')->where(array('cate_id'=>$v['cate_id']))->find();
            $user=db('user')->where('user_id',$uid)->find();
            $date[$k]['img']=db('userdata')->where('uid',$uid)->value('image');
            $date[$k]['name']=$user['name'];
            $date[$k]['classtype']=$classInfo['type'];
            $date[$k]['catename']=$cate['name'];
            $date[$k]['money']=$v['price'];
            $date[$k]['isvip']=$user['is_vip'];
        }
        return json($date);
    }
    function jujue(){
        $id=input('teacherid');
        $order_id=input('order_id');
        $user_id=input('user_id');
        $demandid= db('order')->where('order_id',$order_id)->value('pid');
        $where['class_id']=$id;
        $where['demand_id']=$demandid;
        $date= db('bid')->where($where)->update(['bit_status'=>2]);
        return $this->orderset($user_id,$order_id);

    }

   function xuan(){
       $id=input('teacherid');
       $order_id=input('order_id');
       $user_id=input('user_id');
       $demandid= db('order')->where('order_id',$order_id)->value('pid');
       $pass=md5(md5(input('pass')));
       $userdata=db('userdata')->where(array('uid'=>$user_id))->find();
       $bid=db('bid')->where(array('class_id'=>$id,'demand_id'=>$demandid))->find();
       $demand=db('demand')->where(array('demand_id'=>$demandid))->find();
       //判断选中老师的价格是否高于订单价格
       if($bid['price']>$demand['price']){
           //高于，支付剩余定金
           if($pass==$userdata['paypass']){
               $money=$bid['price']-$demand['price'];
               if($userdata['money']<$money){
                   $data=102;//网约课币 不够
                   return json($data);
               }else{
                   db('userdata')->where(array('uid'=>$user_id))->setDec('money',$money);
                   $mvp['bit_status']=1;
                   db('bid')->where(array('class_id'=>$id,'demand_id'=>$demandid))->update($mvp);
                   $mmp['class_id']=$id;
                   $mmp['status']=1;
                   db('demand')->where(array('uid'=>$user_id))->update($mmp);
                   //修改其他老师为淘汰状态
                   $save['bit_status']=2;
                   db('bid')->where(array('demand_id'=>$demandid,'class_id'=>array('neq',$id)))->update($save);
                   //修改订单为完成状态
                   $o_pmt['finish_status']=1;
                   $o_pmt['status']=1;
                   db('order')->where(array('pid'=>$demandid,'classtype'=>1))->update($o_pmt);
                   return $this->orderset($user_id,$order_id);
               }
           }else{
               $data=101;//密码错误
               return json($data);
           }
       }else{

           //没有加价
           $mvp['bit_status']=1;
           db('bid')->where(array('class_id'=>$id,'demand_id'=>$demandid))->update($mvp);
           //修改其他老师为淘汰状态
           $save['bit_status']=2;
           db('bid')->where(array('demand_id'=>$demandid,'class_id'=>array('neq',$id)))->update($save);
           $mmp['class_id']=$id;
           $mmp['status']=1;
           db('demand')->where(array('uid'=>$user_id))->update($mmp);
           //修改订单为完成状态
           $o_pmt['finish_status']=1;
           $o_pmt['status']=1;
           db('order')->where(array('pid'=>$demandid,'classtype'=>1))->update($o_pmt);

           return $this->orderset($user_id,$order_id);
       }
   }

    //订单详情查询
    function  orderset($uid,$oid){
        $user_id=$uid;
        $orderid=$oid;
        $order=db('order')->where(array('order_id'=>$orderid))->find();
        if($order['classtype']==0){
            $pid=$order['pid'];
            $good=db('goods')->where(array('goods_id'=>$order['pid']))->find();
            $data['oid']=(string)$order['order_id'];
            $data['img']=(string)$good['img'];
            $data['name']=(string)$good['name'];
            $data['introduce']=assoc_substr($good['introduce'],30);
            $data['money']=(string)$order['money'];
            $data['pid']=(string)$good['goods_id'];
            $data['pType']=(string)$good['type'];
            $data['status']=$order['status'];
            $data['ordernum']=(string)$order['num'];
            $data['time']=(string)date('Y-m-d H:i:s',$order['time']);
            if($order['paytype']){
                $data['paytype']=(string)$order['paytype']; //支付方式  0：约课币  1：支付宝  2：微信
            }else{
                $data['paytype']='';
            }

            $data['grouptime']=(string)date('Y-m-d H:i',$good['group_time']); //开团时间
            if($order['buytype']==2){
                $groupbuy=db('groupbuy')->where(array('pid'=>$good['goods_id'],'paystatus'=>1))->count();
                if($groupbuy<$good['group_num']){
                    $data['num']=(string)($good['group_num']-$groupbuy);
                }else{
                    $data['num']='0';
                }
            }else{
                $data['num']='';
            }
            $report=db('report')->where(array('uid'=>$user_id,'order_id'=>$pid))->find();
            if($report){
                $data['report_status']='1';
            }else{
                $data['report_status']='0';
            }
            $class=db('class')->where(array('class_id'=>$good['class_id']))->find();
            if($class['type']==3){
                $data['isOrganization']='1';
            }else{
                $data['isOrganization']='0';
            }
            $tuser=db('user')->where(array('user_id'=>$class['uid']))->find();
            $udrel=db('userdata')->where(array('uid'=>$class['uid']))->find();
            $data['teacherName']=$tuser['name'];
            $data['teacherImgURL']=$udrel['image'];
            $data['startTime']=date('Y-m-d H:i:s',$good['starttime']);
            $data['endTime']=date('H:i:s',$good['endtime']);
            //分类start
            $ca=db('category');
            $cate=$ca->where(array('cate_id'=>$good['cate_id']))->find();
            $cate1=$ca->where(array('cate_id'=>$cate['pid']))->find();
            $cate2=$ca->where(array('cate_id'=>$cate1['pid']))->find();
            $data['className']=(string)$cate2['name'].'|'.$cate1['name'];
            //分类end
            $data['demandid']='';     //需求id
            $data['bid_status']='';  //投标状态
            $data['catename']='';        //三级分类名称
            $data['describe']=''; //需求描述
            $data['demandstatus']='';
            //接单的老师列表
            //查看该条订单是否有选中教师，有的话查出该条
            $data['teacherarr']=array();
            $likelist=db('goods')->where(array('type'=>array('IN','1,2,3,6'),'goods_id'=>array('neq',$pid)))->limit(4)->select();
            if($likelist){
                foreach($likelist as $kk=>$vv){
                    $dataa[$kk]['pid']=(string)$vv['goods_id'];
                    $dataa[$kk]['name']=$vv['name'];
                    $dataa[$kk]['pType']=(string)$vv['type'];
                    $dataa[$kk]['number']=(string)$vv['number'];
                    $dataa[$kk]['img']=$vv['img'];
                    $dataa[$kk]['pBuyType']=(string)$vv['price_status'];
                    $dataa[$kk]['oldPrice']=(string)$vv['money'];
                    if($vv['price_status']==0){
                        $dataa[$kk]['price']=(string)$vv['money'];
                    }else{
                        $dataa[$kk]['price']=(string)$vv['discount_money'];
                    }
                    $likeclass=db('class')->where(array('class_id'=>$vv['class_id']))->find();
                    if($likeclass['type']==3){
                        $dataa[$kk]['isOrganization']='1';
                    }else{
                        $dataa[$kk]['isOrganization']='0';
                    }
                }
                $data['g_like']=$dataa;
            }else{
                $data['g_like']=array();
            }
            $data['type']=1;//不是托管
        }else{
            $data['oid']=(string)$order['order_id'];        //订单id
            $data['img']='';
            $data['name']='';
            $data['introduce']='';
            $data['money']=(string)$order['money'];     //订单金额
            $data['pid']='';
            $data['pType']='';
            $data['status']=(string)$order['status'];   //订单状态
            $data['ordernum']=(string)$order['num'];    //订单号
            $data['paytype']='';
            $data['time']=(string)date('Y-m-d H:i:s',$order['time']);   //下单时间
            $data['grouptime']='';
            $data['num']='';
            $data['report_status']='';
            $data['isOrganization']='';
            $data['teacherName']='';
            $data['teacherImgURL']='';
            $data['startTime']='';
            $data['endTime']='';
            $data['className']='';
            $demand=db('demand')->where(array('demand_id'=>$order['pid']))->find();
            $data['demandid']=(string)$demand['demand_id'];     //需求id
            $data['bid_status']=(string)$demand['status'];  //投标状态
            $cate=db('category')->where(array('cate_id'=>$demand['cate_id']))->find();
            $data['catename']=$cate['name'];        //三级分类名称
            $describe=db('describe')->where(array('demand_id'=>$demand['demand_id']))->find();
            $data['describe']=json_decode($describe['content']); //需求描述
            $data['demandstatus']=$demand['status'];
            //接单的老师列表
            //查看该条订单是否有选中教师，有的话查出该条
            $bid=db('bid')->where(array('demand_id'=>$order['pid'],'bit_status'=>1))->find();
            if($bid){
                $class=db('class')->where(array('class_id'=>$bid['class_id']))->find();
                $biduser=db('user')->where(array('user_id'=>$class['uid']))->find();
                $data['teacherarr']=array(
                    array(
                        'teacherid'         =>  $class['class_id'],
                        'teacherimg'        =>  $class['img'],
                        'teachername'       =>  $class['name'],
                        'teacherintroduce'  =>  $class['introduce'],
                        'teachergrade'      =>  $class['grade'],
                        'money'             =>  $bid['price'],
                        'choice'            =>  '1',
                        'phone'             =>  $biduser['phone'],
                    ),

                );
                if($class['type']==3){
                    $data['teacherarr'][0]['isOrganization']='1';
                }else{
                    $data['teacherarr'][0]['isOrganization']='0';
                }
            }else{
                //没有选中教师，查询出所有接单教师列表
                $bidwhere['demand_id']=$order['pid'];
                $bidwhere['bit_status']=0;
                $bidlist=db('bid')->where($bidwhere)->select();
                if($bidlist){
                    foreach($bidlist as $k=>$v){
                        $class=db('class')->where(array('class_id'=>$v['class_id']))->find();
                        $biduser=db('user')->where(array('user_id'=>$class['uid']))->find();
                        $dataa[$k]['teacherid']=$class['class_id'];
                        $dataa[$k]['teacherimg']=$class['img'];
                        $dataa[$k]['teachername']=$class['name'];
                        $dataa[$k]['teacherintroduce']=$class['introduce'];
                        $dataa[$k]['teachergrade']=$class['grade'];
                        $dataa[$k]['money']=$v['price'];
                        $dataa[$k]['choice']='0';
                        $dataa[$k]['phone']=$biduser['phone'];
                        if($class['type']==3){
                            $dataa[$k]['isOrganization']='1';
                        }else{
                            $dataa[$k]['isOrganization']='0';
                        }
                    }
                    $data['teacherarr']=$dataa;
                }else{
                    $data['teacherarr']=array();
                }

            }

            $data['g_like']=array();
            $data['type']=2;//是托管

        }
        return json($data);
    }
    //订单详情
    function  orderdetails(){
        $user_id=input('user_id');
        $orderid=input('order_id');
        return $this->orderset($user_id,$orderid);
}

   //淘汰老师查询
    function  taotai(){
        $data=array();
        $oid=input('order_id');
        $order=db('order')->where(array('order_id'=>$oid))->find();
        $bidwhere['demand_id']=$order['pid'];
        $bidwhere['bit_status']=2;
        $bid=db('bid')->where($bidwhere)->select();
        foreach($bid as $k=>$v){
            $class=db('class')->where(array('class_id'=>$v['class_id']))->find();
            $user=db('user')->where(array('user_id'=>$class['uid']))->field('is_vip')->find();
            $data[$k]['is_vip']=$user['is_vip'];
            $data[$k]['teacherid']=$class['class_id'];
            $data[$k]['money']=$v['price'];
            if($class['img']){
                $data[$k]['teacherimg']=$class['img'];
            }else{
                $data[$k]['teacherimg']='';
            }
            $data[$k]['teachername']=$class['name'];
            $data[$k]['teacherintroduce']=$class['introduce'];
            $data[$k]['teachergrade']=(string)$class['grade'];
            if($class['type']==3){
                $data[$k]['isOrganization']='1';
            }else{
                $data[$k]['isOrganization']='0';
            }
        }
        return json($data);
    }

   //修改订单详情
    function toOrderIdChangOrderInfo(){
        $order_id=input('order_id');
        $pid= db('order')->where('order_id',$order_id)->value('pid');
        $arrayimg=input('arrayimg');
        $sendAudioList=input('sendAudioList');
        $longtime=input('longtime');
        $inputvalue_textarea=input('inputvalue_textarea');
        $Updescribe= db('describe')->insertGetId(["demand_id"=>$pid,"time"=>time(),"content" => $inputvalue_textarea, "voice" => $sendAudioList,"img" => $arrayimg,"voice_time" => $longtime]);
        return json($Updescribe);
    }
    //关闭需求
    function  closeOrder(){
        $uid=input('uid');
        $order_id=input('order_id');
        $pid= db('order')->where('order_id',$order_id)->value('pid');
        $demand=db('demand')->where(array('demand_id'=>$pid))->find();
        if($uid!=$demand['uid']){
            return json(101);
        }
        if(empty($demand['class_id'])){
            //需求更改为失效
            $dv['status']=2;
            db('demand')->where(array('demand_id'=>$pid))->update($dv);
            //订单改为取消
            $ov['finish_status']=2;
            $ov['status']=2;
            db('order')->where(array('pid'=>$pid,'classtype'=>1))->update($ov);
            //用户退钱
            db('userdata')->where(array('uid'=>$uid))->setInc('money',$demand['price']);
            //增加用户退款交易记录
            $mvp=array(
                'uid'       =>  $uid,
                'type'      =>  1,
                'time'      =>  time(),
                'income'    =>  $demand['price'],
                'cid'       =>  $demand['demand_id'],
                'source'    =>  '定制课退款',
                'ptype'     =>  2,
                'classtype' =>  1
            );
           $payrecordset= db('payrecord')->insert($mvp);
            if($payrecordset){
                return json(1);
            }
        }else{
            return json(101);
        }
    }
   //历史搜索
    function  hotsearch(){
        $search=db('search');
        $data=$search->order('number desc')->field('name')->limit(10)->select();
        return json($data);
    }
    //搜索
    function search(){
            $content=input('content');
            // 根据搜索内容添加到搜索表
            $search=db('search');
            $rel=$search->where(array('name'=>$content))->find();
            // 判断搜索表有没有数据，有则搜索次数+1 ，没有则创建
            if($rel){
                $mvp['number']=$rel['number']+1;
                $search->where('search_id='.$rel['search_id'])->update($mvp);
            }else{
                $mvp['name']=$content;
                $mvp['number']=1;
                $search->insertGetId($mvp);
            }

            $good=db('goods');
            $where['name']=array('like','%'.$content.'%');
            $where['endtime']=array('gt',time());
            $where['type']=array('IN','1,6');
            $where['status']=0;
            $where['del_status']=0;
            $list=$good->where($where)->limit(4)->select();
            foreach($list as $key=>$val){
                $date[$key]['pImgURL']=$val['img'];
                $date[$key]['pid']=(string)$val['goods_id'];
                $date[$key]['pName']=$val['name'];
                $date[$key]['pType']=(string)$val['type'];
                $class=db('class')->where(array('class_id'=>$val['class_id']))->find();
                if($class['type']==3){
                    $date[$key]['isOrganization']='1';
                }else{
                    $date[$key]['isOrganization']='0';
                }
                $date[$key]['recommend']=(string)$val['recommend'];
                $date[$key]['signUpNum']=(string)$val['number'];
                $date[$key]['pBuyType']=(string)$val['price_status'];
                $heard=strstr($_SERVER['HTTP_USER_AGENT'],'(',true);
                if($heard=='TCCM_WYK/4.0.1 ' || $heard=='TCCM_WYK/4.0.1'){
                    $date[$key]['oldPrice']='0';
                    $date[$key]['currentPrice']='0';
                }else{
                    $date[$key]['oldPrice']=(string)$val['money'];      //原价
                    if($val['price_status']==0){
                        $date[$key]['currentPrice']=(string)$val['money']; //折扣价
                    }else{
                        $date[$key]['currentPrice']=(string)$val['discount_money']; //折扣价
                    }
                }
                $date[$key]['starttime']=date('Y-m-d H:i:s',$val['starttime']);
            }
            $data[0]['name']='直播';
            $data[0]['img']='';
            if(empty($date)){
                $data[0]['arr']=array();
            }else{
                $data[0]['arr']=$date;
            }
            $where1['name']=array('like','%'.$content.'%');
            $where1['type']=array('IN','2,3,4');
            $where1['status']=0;
            $where1['del_status']=0;
            $list2=$good->where($where1)->limit(4)->select();
            foreach($list2 as $key=>$val){
                $date2[$key]['pImgURL']=$val['img'];
                $date2[$key]['pid']=(string)$val['goods_id'];
                $date2[$key]['pName']=$val['name'];
                $date2[$key]['pType']=(string)$val['type'];
                $class=db('class')->where(array('class_id'=>$val['class_id']))->find();
                if($class['type']==3){
                    $date2[$key]['isOrganization']='1';
                }else{
                    $date2[$key]['isOrganization']='0';
                }
                $date2[$key]['recommend']=(string)$val['recommend'];
                $date2[$key]['signUpNum']=(string)$val['number'];
                $date2[$key]['pBuyType']=(string)$val['price_status'];
                $heard=strstr($_SERVER['HTTP_USER_AGENT'],'(',true);
                if($heard=='TCCM_WYK/4.0.1 ' || $heard=='TCCM_WYK/4.0.1'){
                    $date2[$key]['oldPrice']='0';
                    $date2[$key]['currentPrice']='0';
                }else{
                    $date2[$key]['oldPrice']=(string)$val['money'];      //原价
                    if($val['price_status']==0){
                        $date2[$key]['currentPrice']=(string)$val['money']; //折扣价
                    }else{
                        $date2[$key]['currentPrice']=(string)$val['discount_money']; //折扣价
                    }
                }
            }
            $data[1]['name']='视频';
            $data[1]['img']='';
            if(empty($date2)){
                $data[1]['arr']=array();
            }else{
                $data[1]['arr']=$date2;
            }
            $data= array_merge($data[1]['arr'],$data[0]['arr']);
            return json($data);
    }

    function describeinfo(){
        $demandid=input('demandid');
        $demand=db('demand')->where(array('demand_id'=>$demandid))->find();
        $data['demandstatus']=$demand['status'];
        $describe=db('describe')->where(array('demand_id'=>$demandid))->order('time')->select();
        $cate=db('category')->where(array('cate_id'=>$demand['cate_id']))->find();
        $data['cate']=$cate['name'];
        foreach($describe as $k=>$v){
            $data['data'][$k]['time']=date('Y.m.d H:i',$v['time']);
            $data['data'][$k]['content']=json_decode($v['content']);
            if($v['voice']){
                $data['data'][$k]['voice']=$v['voice'];
            }else{
                $data['data'][$k]['voice']='';
            }
            $data['data'][$k]['voice_time']=$v['voice_time'];
            if($v['img']){
                $data['data'][$k]['img']=explode(',',$v['img']);
            }else{
                $data['data'][$k]['img']='';
            }
        }
        $data['datao'] =array_slice($data['data'],0,1);
        $data['datat'] =array_slice($data['data'],1);
        return json($data);
    }

    //搜索更多
    function searchmore(){
        $content=input('content');
        $sort=input('sort');
        $time=time();
        if($sort=='1'){
            $order=' order by number desc';
        }else if($sort=='2'){
            $order='order by money asc';
        }else if($sort=='3'){
            $order='order by money desc';
        }else{
            $order='';
        }
        $where=' select * from goods where  (endtime IS NULL OR endtime > '.$time.' )and status=0 and del_status=0 and type IN (2,3,1,6) and name like "%'.$content.'%"  '.$order;
        $goodsinfo=db('goods')->query($where);
        foreach($goodsinfo as $key=>$val){
            $date[$key]['pImgURL']=$val['img'];
            $date[$key]['pid']=$val['goods_id'];
            $date[$key]['pName']=$val['name'];
            $date[$key]['signUpNum']=(string)$val['number'];
            $date[$key]['classhour']=(string)$val['classhour'];
            $date[$key]['time']=date('Y年m月d日 H:i:s',$val['grounding_time']);
            $date[$key]['starttime']=date('Y年m月d日 H:i:s',$val['starttime']);
            $date[$key]['sonClassAmount']=(string)$val['classhour'];
            $date[$key]['openSaleTime']=date('Y-m-d H:i:s',$val['grounding_time']);
            $date[$key]['pType']=(string)$val['type'];
            $date[$key]['pBuyType']=(string)$val['price_status'];
            $heard=strstr($_SERVER['HTTP_USER_AGENT'],'(',true);
            if($heard=='TCCM_WYK/4.0.1 ' || $heard=='TCCM_WYK/4.0.1'){
                $date[$key]['oldPrice']='0';
                $date[$key]['currentPrice']='0';
            }else{
                $date[$key]['oldPrice']=(string)$val['money'];      //原价
                if($val['price_status']==0){
                    $date[$key]['currentPrice']=(string)$val['money']; //折扣价
                }else{
                    $date[$key]['currentPrice']=(string)$val['discount_money']; //折扣价
                }
            }
            $date[$key]['recommend']=(string)$val['recommend'];
            $date[$key]['openSaleTime']=date('Y-m-d H:i:s',$val['grounding_time']);
            $date[$key]['sonClassAmount']=(string)$val['classhour'];
            $class=db('class')->where(array('class_id'=>$val['class_id']))->find();
            $udrel=db('userdata')->where(array('uid'=>$class['uid']))->find();
            if($class['type']!=3){
                $date[$key]['isOrganization']='0';
            }else{
                $date[$key]['isOrganization']='1';
            }
            $date[$key]['teacherName']=$class['name'];
            $date[$key]['teacherImg']=$udrel['image'];
            $date[$key]['endSaleTime']=(string)date('Y年m月d日 H:i:s',$val['sign_endtime']);
            $date[$key]['liveTime']=(string)round(($val['endtime']-$val['starttime'])/60);

        }



        return json($date);
    }


    function  xiaoxi(){
        $uid=input('uid');
        $userrel=db('user')->where(array('user_id'=>$uid))->find();
        if($userrel){
            $rong=db('rong_history_mes');
            $newwhere='receiver_id='.$userrel['phone'].' OR sender_id='.$userrel['phone'];
            $ronglist=$rong
                ->where($newwhere)
                ->order('send_time desc')
                ->find();
            if($ronglist){
                $date[0]=array(
                    'icon'      =>  '/user/public_liaotian.png',
                    'name'      =>  '聊天消息',
                    'content'   =>  '',
                    'time'      =>  date('Y-m-d H:i',$ronglist['send_time']),
                    'type'      =>  'chat',
                    'status'    =>  '1'
                );
            }else{
                $date[0]=array(
                    'icon'      =>  '/user/public_liaotian.png',
                    'name'      =>  '聊天消息',
                    'content'   =>  '',
                    'time'      =>  date('Y-m-d H:i',$ronglist['send_time']),
                    'type'      =>  'chat',
                    'status'    =>  '0'
                );
            }
            $news=db('news');
            $newsread=db('newsread');
            $where['uid']=array('exp','is null');
            $where['tuisong']='1';
            $newsrel=$news->field('content,time')->where($where)->order('time desc')->find();
            if($newsrel){
                $date[1]=array(
                    'icon'      =>  '/user/public_xitong.png',
                    'name'      =>  '系统消息',
                    'content'   =>  $newsrel['content'],
                    'time'      =>  date('Y-m-d H:i',$newsrel['time']),
                    'type'      =>  'sys'
                );
                $newsreadrel=$newsread->where(array('uid'=>$userrel['user_id']))->find();
                if($newsreadrel){
                    if($newsreadrel['status']=='0'){
                        $date[1]['status']='1';
                    }else{
                        $date[1]['status']='0';
                    }
                }else{
                    $date[1]['status']='0';
                }

            }else{
                $date[1]=array(
                    'icon'      =>  '/user/public_xitong.png',
                    'name'      =>  '系统消息',
                    'content'   =>  '',
                    'time'      =>  '',
                    'type'      =>  'sys',
                    'status'    =>  '0'
                );
            }

            $where_me['uid']=$userrel['user_id'];
            $where_me['type']=1;
            $where_me['tuisong']='1';
            $news_me=$news->field('content,time')->where($where_me)->order('time desc')->find();
            if($news_me){
                $date[2]=array(
                    'icon'      =>  '/user/public_geren.png',
                    'name'      =>  '个人消息',
                    'content'   =>  $news_me['content'],
                    'time'      =>  date('Y-m-d H:i',$news_me['time']),
                    'type'      =>  'me',
                );
                $where_me['status']='0';
                $news_merel=$news->where($where_me)->find();
                if($news_merel){
                    $date[2]['status']='1';
                }else{
                    $date[2]['status']='0';
                }

            }else{
                $date[2]=array(
                    'icon'      =>  '/user/public_geren.png',
                    'name'      =>  '个人消息',
                    'content'   =>  '',
                    'time'      =>  '',
                    'type'      =>  'me',
                    'status'    =>  '0'
                );
            }
            $where_jiaoyi['uid']=$userrel['user_id'];
            $where_jiaoyi['type']=2;
            $where_jiaoyi['tuisong']='1';
            $news_jiaoyi=$news->field('content,time')->where($where_jiaoyi)->order('time desc')->find();
            if($news_jiaoyi){
                $date[3]=array(
                    'icon'      =>  '/user/public_jiaoyi.png',
                    'name'      =>  '交易消息',
                    'content'   =>  $news_jiaoyi['content'],
                    'time'      =>  date('Y-m-d H:i',$news_jiaoyi['time']),
                    'type'      =>  'buy'
                );
                $where_jiaoyi['status']='0';
                $news_jiaoyirel=$news->where($where_jiaoyi)->find();
                if($news_jiaoyirel){
                    $date[3]['status']='1';
                }else{
                    $date[3]['status']='0';
                }

            }else{
                $date[3]=array(
                    'icon'      =>  '/user/public_jiaoyi.png',
                    'name'      =>  '交易消息',
                    'content'   =>  '',
                    'time'      =>  '',
                    'type'      =>  'buy',
                    'status'    =>  '0'
                );
            }

            $arr['group']=$date;

            return json($arr);
        }
    }
    //问题
    function wenti(){
       $wenti= db('wenti')->select();
        foreach ($wenti as $k=>$v){
            $wenti[$k]['status']=1;
        }
        return json($wenti);
    }
    //协议
    function xieyi(){
        $xieyi= db('xieyi')->select();
        return json($xieyi);
    }
    //首页
    function indexinfo(){
        //taskstatus  0 不可以 1可以 3已领取
        $goods=db('goods');
        $goodlist=$goods
            ->where(array('cate_id'=>array('IN',$cateid),'status'=>'0','del_status'=>'0'))
            ->field('goods_id,name,price_status,classhour,grounding_time,endtime,type,img,class_id,number,money,discount_money,group_num,group_time,starttime,sign_endtime')
            ->limit(2)
            ->order('time desc')
            ->select();
        $date=array();
        foreach($goodlist as $key=>$val){
            $date[$key]['pid']=(string)$val['goods_id'];                //课程id
            $date[$key]['pName']=(string)$val['name'];                  //课程名字
            $date[$key]['sonClassAmount']=(string)$val['classhour'];    //套课的课节数
            $date[$key]['openSaleTime']=(string)date('Y-m-d H:i:s',$val['grounding_time']); //普通课程上架时间
            $date[$key]['endSetClassTime']=(string)date('Y-m-d H:i:s',$val['endtime']);     //套课结束上传时间
            $date[$key]['pType']=(string)$val['type'];                  //课程类型，具体类型见QQ群公告
            $date[$key]['pBuyType']=(string)$val['price_status'];       // 价格状态
            $date[$key]['pImgURL']=(string)URL.$val['img'];                 //课程封面图片
            $isOrganization=db('class')->where(array('class_id'=>$val['class_id']))->field('type')->find();
            if($isOrganization['type']==3){
                $date[$key]['isOrganization']='1';   //是否机构上传   是
            }else{
                $date[$key]['isOrganization']='0';   //是否机构上传   否
            }
            $date[$key]['signUpNum']=(string)$val['number'];
            $heard=strstr($_SERVER['HTTP_USER_AGENT'],'(',true);
            if($heard=='TCCM_WYK/4.0.1 ' || $heard=='TCCM_WYK/4.0.1'){
                $date[$key]['oldPrice']='0';
                $date[$key]['currentPrice']='0';
            }else{
                $date[$key]['oldPrice']=(string)$val['money'];      //原价
                if($val['price_status']==0){
                    $date[$key]['currentPrice']=(string)$val['money']; //折扣价
                }else{
                    $date[$key]['currentPrice']=(string)$val['discount_money']; //折扣价
                }
            }
            $date[$key]['groupBuyNum']=(string)$val['group_num'];
            $date[$key]['groupBuyEndTime']=(string)date('Y-m-d H:i:s',$val['group_time']);
            $date[$key]['liveStartTime']=(string)date('Y-m-d H:i:s',$val['starttime']);
            $date[$key]['liveEndBuyTime']=(string)date('Y-m-d H:i:s',$val['starttime']);
            $date[$key]['liveTime']=(string)round(($val['endtime']-$val['starttime'])/60);
        }
    }
    function  mianfei(){
     $add_where['cid']=input('goods_id');
     $add_where['uid']=input('uid');
     $add_where['type']=1;
     $add_where['time']=time();
     $add_where['income']=0;
     $payrel = db('payrecord')->insertGetId($add_where);
     return json($payrel);
    }
    function setmyinfo(){
//      type 1 头像 2昵称 3性别 4出生日期 5地区 6个人简介
        $value=input('value');
        $type=input('type');
        $uid=input('uid');
        if($type==1){
            $upwhere['image']=$value;
        }elseif($type==2){//修改昵称 是在 user表中
            $upwhere['name']=$value;
            $user=  db('user')->where('user_id',$uid)->update($upwhere);
            if($user!==false){
                return json(1);
            }
            return json($user);
        }elseif($type==3){
            $upwhere['sex']=$value;
        }elseif($type==4){
            $upwhere['birthday']=$value;
        }elseif($type==5){
            $upwhere['address']=$value;
        }elseif($type==6){
            $upwhere['profile']=$value;
        }
      $userdata=  db('userdata')->where('uid',$uid)->update($upwhere);
        if($userdata!==false){
            return json(1);
        }
    }
    function newsdetail(){
        $id=input('nid');
        $news= db('news')->find($id);
        return json($news);
    }


    function  taskinfo(){
        $today = strtotime(date("Y-m-d"),time());
        $uid=input('uid');
        $etoday= $today+86399;
        $user=db('user')->where('user_id',$uid)->find();
        if($user){
            $data[0]=array(
                'taskid'        =>  '1',
                'taskname'      =>  '每日在线观看视频30分钟',
                'taskreward'    =>  '20',
            );
            $tasksee=db('task')->where(array('uid'=>$user['user_id'],'time'=>array('egt',$today),'type'=>1))->find();
            if($tasksee){
                $data[0]['taskstatus']='3';
            }else{
                $look=db('looklength')->where(array('uid'=>$user['user_id'],'time'=>array('egt',$today)))->find();
                if($look){
                    if($look['length']>30*60){
                        $data[0]['taskstatus']='1';
                    }else{
                        $data[0]['taskstatus']='0';
                    }
                }else{
                    $data[0]['taskstatus']='0';
                }

            }

            $where['time']=array(array('egt',$today),array('elt',$etoday));
            $where['uid']=$user['user_id'];
            $where['type']=2;
            $where['ctype']=array('IN','1,5,6');
            $buyliveb=db('payrecord')->where($where)->find();
            $data[1]=array(
                'taskid'        =>  '2',
                'taskname'      =>  '每日购买直播课一次',
                'taskreward'    =>  '20',
            );

            if($buyliveb){
                $taskliveb=db('task')->where(array('uid'=>$user['user_id'],'time'=>array('egt',$today),'type'=>2))->find();
                if($taskliveb){
                    $data[1]['taskstatus']='3';
                }else{
                    $data[1]['taskstatus']='1';
                }

            }else{
                $data[1]['taskstatus']='0';
            }
            $where['ctype']=array('IN','2,3');
            $buyvideo=db('payrecord')->where($where)->find();
            $data[2]=array(
                'taskid'        =>  '3',
                'taskname'      =>  '每日购买视频课一次',
                'taskreward'    =>  '20',
            );
            if($buyvideo){
                $taskvideo=db('task')->where(array('uid'=>$user['user_id'],'time'=>array('egt',$today),'type'=>3))->find();
                if($taskvideo){
                    $data[2]['taskstatus']='3';
                }else{
                    $data[2]['taskstatus']='1';
                }
            }else{
                $data[2]['taskstatus']='0';
            }
            return json($data);
        }
    }

    function clicktask(){
        $uid=input('uid');
        $taskid=input('taskid');
        $user=db('user')->where('user_id',$uid)->find();
        if($user){
            $ud=db('userdata');
            $today = strtotime(date("Y-m-d"),time());
            $etoday= $today+86399;
            $where['time']=array('egt',$today);
            $where['uid']=$user['user_id'];
            $where['type']=2;
            if($taskid=='1'){
                $look=db('looklength')->where(array('uid'=>$user['user_id'],'time'=>array('egt',$today)))->find();
                if($look['length']<30*60){
                    $data=202;
                    return json($data);
                    exit();
                }
                $taskrel=db('task')->where(array('uid'=>$user['user_id'],'time'=>array('egt',$today),'type'=>1))->find();
                if($taskrel){
                    $data=203;
                    return json($data);
                    exit();
                }
                $mvp['type']=1;
            }else if($taskid=='2'){
                $where['ctype']=array('IN','1,5,6');
                $buyliveb=db('payrecord')->where($where)->find();
                if(!$buyliveb){
                    $data=204;
                    return json($data);
                    exit();
                }
                $taskrel=db('task')->where(array('uid'=>$user['user_id'],'time'=>array('egt',$today),'type'=>2))->find();
                if($taskrel){
                    $data=205;
                    return json($data);
                    exit();
                }
                $mvp['type']=2;
            }else if($taskid=='3'){
                $where['ctype']=array('IN','2,3');
                $buyvideo=db('payrecord')->where($where)->find();
                if(!$buyvideo){
                    $data=206;
                    return json($data);
                    exit();
                }
                $taskrel=db('task')->where(array('uid'=>$user['user_id'],'time'=>array('egt',$today),'type'=>3))->find();
                if($taskrel){
                    $data=207;
                    return json($data);
                    exit();
                }
                $mvp['type']=3;
            }
            $ud->where(array('uid'=>$user['user_id']))->setInc('integral','20');
            $mvp['uid']=$user['user_id'];
            $mvp['time']=time();
            $task=db('task')->where(array('uid'=>$user['user_id'],'type'=>$taskid))->find();
            if($task){
                db('task')->where(array('uid'=>$user['user_id']))->save($mvp);
            }else{
                db('task')->insertGetId($mvp);
            }
            //添加积分收入记录
            $integral=array(
                'uid'       =>  $user['user_id'],
                'type'      =>  1,
                'source'    =>  '任务奖励',
                'num'       =>  20,
                'time'      =>  time()
            );
            $datainfo= db('integral')->insertGetId($integral);
            return json($datainfo);
            exit();
        }
    }
    function duihuan(){
        $uid=input('uid');
        $code=input('code');//要兑换的积分
        $integral=db('userdata')->where('uid',$uid)->value('integral');
        if($code>$integral){
            $data=101;
            return json($data);
            exit();
        }else{
            $integralm=db('userdata')->where('uid',$uid)->setInc('money',$code/100);
            $integrali=db('userdata')->where('uid',$uid)->setDec('integral',$code);
            if($integralm&&$integrali){
                $data=100;
                return json($data);
                exit();
            }else{
                $data=102;
                return json($data);
                exit();
            }
        }

    }
    //删除审核状态
    function deleteProve(){
        $uid=input('uid');
        if(empty($uid)){
            return json(0);
        }
        $de['uid']=$uid;
        $data=db('prove')->where($de)->delete();
        return json($data);
    }
    //验证支付密码
    function oldPassVer(){
        $uid=input('uid');
        $paypassword=md5(md5(input('password')));
        $where['paypass']=$paypassword;
        $where['uid']=$uid;
        $uindo=db('userdata')->where($where)->find();
        if($uindo){
         return 100;
        }else{
         return 101;
        }
    }
}



